PHP & Web Development Blogs

Search Results For: security
Showing 1 to 5 of 8 blog articles.
1714 views · 4 weeks ago

![Ideas to help your PHP dev team grow their skills](https:/ /cdn.filestackcontent.com/LcqSW9KZSZarYYZWaQVH)

> Your biggest asset is also your biggest risk... your developers

Your business thrives because of the incredible work and innovation of your developers. With simple keystrokes your developers can completely transform your business, add new features, and drive new sales.

But those same keystrokes can take down production, create security back doors, and put your business at risk. That's why it's more important than ever for your team members to be up to speed with the latest technology, especially around performance and security.

Of course, some things are easier said than done - after all everyone is super busy these days. So how can you help keep your team members learning, and putting your business first in the process?

## Conference Parties

There's nothing better than attending a [PHP or programming conference](https:/ /www.php.net/conferences/) in person - the chance to meet speakers face to face, to network, the knowledge, and the hallway track. However, many companies aren't able to afford multiple (or even one) conference for their developers - especially ones that require airfare and hotel.

However, that doesn't mean you shouldn't still participate in these conferences. The good news is that roughly once a quarter [Nomad PHP](/live) streams talks from a conference right to your computer. This means that your team members can all participate in a multi-day conference from the comfort of your office (or their home) - and you can provide this for your team for [less than the cost](/teams) of a single conference ticket!

Make the conference party even more special by providing lunch during the lunch break, bringing in party gifts, having give-aways during the conference, and planning activities during longer breaks for your team.

Since many conferences take place on Friday, not only are you providing invaluable training and an incredible work benefit, but ending the week on a super positive note that your team members will appreciate (and your risk assessment teams will greatly appreciate as new security practices and compliance practices are put into place).

## Monthly Lunch and Learns

Every month Nomad PHP offers [live virtual talks](/live) by the industry's top experts. With talks at 11am Pacific, and 6pm Pacific it's a perfect time to grab a conference room and order a couple pizzas for lunch (or if Eastern, grab some snacks and maybe a beer) and play the monthly meeting on the large screen.

Your team members will have the opportunity to take notes, discuss with each other, and perhaps most importantly ask the speaker real-world questions that directly impact your business, providing tangible solutions to the problems they are facing.

And since every Nomad PHP Pro meeting [is recorded](/videos), your team members can refer back to the video at any time, watching sections relevant to them or digging in for more information.

## Developer Book Club

Encourage your team members to share what they're learning with others, and help build each other up. Not only are you helping grow skills and ensure your team is following the latest best practices, but you're also fostering a mentor-mentality within your team - where each team member feels invested in the growth of other members.

With Nomad PHP you receive a new issue of [php[architect]](/books) each month and have several [additional books](/books) available to read on demand - providing the latest updates and an invaluable resource to help your book club get started.

## Developer Movie Nights

Sometimes we all just want to get away, grab some popcorn, and watch a movie. Similar to lunch and learns, give your developers a night or two where they can get together and watch one of the [250+ training videos](/videos) available on Nomad PHP. You can even make it a movie marathon!

Whether it's pizza, popcorn, sodas, beers - your team members will have the chance to kick back, relax a bit, build team camaraderie, and learn valuable skills to help your business succeed. Essentially, turning a training day into a fun team-bonding activity.

## Learning Path Challenges

Every company has challenges, and areas they need their team members to master. Whether it's [DevOps](/videos/devops) and [containerization](/videos/containerization), [security](/videos/security), [performance](/videos/performance), [management](/search/videos/soft-skills?search_query=manage), [modernization](/videos/upgrading), or [soft skills](/videos/soft-skills) - work with your team to determine what skills will help them succeed and work with your team members to put together video learning paths.

Your team members can watch through these [videos on-demand](/videos), go back and replay to refresh their knowledge, and work their way towards mastery in the subjects that will help your company succeed.

## Certification

Show that you are invested in your developers by helping them earn [Professional Certification](/certification). These certifications demonstrate that your team members have a fundamental grasp of the technology they are working with and understand when and how to use this technology.

With [free certification exams](/certification) included with Nomad PHP - you no longer have to worry about failed exams or expensive test credits. Your team members can take the exams at their own pace, discover the areas they need to improve, and take the exam again when they are ready. After all, shouldn't the goal of certification be to help your developers learn these skills and prove their expertise?

You can go even further with certifications by having a special [company award](https:/ /amzn.to/359HSLd), [framing their certificate](https:/ /amzn.to/2SnEOpV), or calling out newly certified developers at team meetings or all-hands.

## Learning Incentives/ Rewards

Of course there are even more ways you can help your developers learn new skills, grow their careers, and build loyalty within your company. With Nomad PHP there are numerous ways for your team members to grow their skills, and numerous ways you can reward/ incentivize them - from rewards for the most active learner, to setting goals for learning new skills, to obtaining certifications, to attending streams, to watching videos on-demand. All of these are included with our [Professional Nomad PHP Team subscriptions](/teams).

### Want to learn more about getting a Nomad Team Subscription for your developers? Give us a call (844) CODE-PHP

**Have more ideas on how to help your developers grow their skills or help employers make education more accessible? Please leave your ideas in the comments below!**

1043 views · 1 months ago

![](https:/ /cdn.filestackcontent.com/ZriVX3EQNqmKgVF9FEdy)

#### Welcome back!, if you’re new please be sure to read [Part 1 here](https:/ /nomadphp.com/blog/1925/code-with-me-challenge-custom-cms-development-with-php-and-mysql).

This tutorial will focus primarily on Security and will touch on how to plan functionality.

Planning out an application and seeing progress regularly is a good strategy as you are most likely to complete your tasks in a timely fashion with this approach.

Ready?, ok let’s jump into it!

### DISCLAIMER

> We highly recommend that you follow these tutorials on a localhost testing server like Uniserver. Read through [Part 1 here](https:/ /nomadphp.com/blog/1925/code-with-me-challenge-custom-cms-development-with-php-and-mysql) to look at our recommendations. These tutorials follow a phased approach and it is highly recommended that you do not make snippets of code live prior to completing this tutorial series.

## Where we left off – the serious stuff.

In the previous tutorial we saved variables to the database.

It’s important to note that further steps are needed to ensure that data transactions to / from the database are secure.

A great first step is to ensure that all POST data (data transmitted after a user clicks a form’s submit button) is sanitized.

## What we’re trying to prevent

One of the most common exploits is SQL Injection, an attack most commonly used to insert SQL into db queries. POST data that’s not sanitized leaves a huge security hole for malicious exploits. In some cases SQL injection can be leveraged to rage an all out assault on a server’s operating system.

A few examples of a basic version of what this might look like can be seen below.

![](https:/ /cdn.filestackcontent.com/GdjoE6bPRQOT582LSGNQ)

#### OUTCOME

This might delete your database table

![](https:/ /cdn.filestackcontent.com/MlAzWxaJQWqsy7MjFQiM)

#### OUTCOME

This might provide access to the entire user table and the password protected area/dashboard.

***Please note that there are various types of SQL injection techniques and I will delve into this during the course of this series.***

## So what exactly is sanitization and what does it do?

When sanitizing POST data, we are essentially looking for any special characters that are often used in SQL injection attacks.

In many ways, this tiny piece of code is the unsung superhero of many database driven applications.

## Let’s secure that POST data!

Navigate to your backend folder and open index.php

Locate the following line of code:

```

$sql = "INSERT INTO content(title,content,author)VALUES ('".$_POST["title"]."', '".$_POST["content"]."', '".$_POST["author"]."')";

```

Ok, let’s get to work.

Based on what I mentioned a few moments ago, it’s clear that our SQL statement is vulnerable so we need to sanitize the POST data pronto!

The method I will focus on first is $mysqli->real_escape_string. This will escape any special characters found in the POST data.

Add the following just above your $sql.

```php

$title = $letsconnect -> real_escape_string($_POST['title']);

$content = $letsconnect -> real_escape_string($_POST['content']);

$author = $letsconnect -> real_escape_string($_POST['author']);

```

Did you notice the use of `$letsconnect`? This was used because of our db connection defined in conn.php.

Our new query will look like this:

```

$sql = "INSERT INTO content (title,content,author) VALUES ('".$title."', '".$content."', '".$author."')";

```

Go ahead and replace the old `$sql`.

Phew!, we can breathe easy now.

## Next, let’s lighten things up a bit by focusing on functionality and aesthetics.

A phased approach is the best way to tackle projects of any size.

I tend to jot this down on paper before creating a more legible professional spec!.

Typically the phased approach lends itself to logical progression.

For example, over the next several days I will go over the following:

* Account Access

* The login process

* The registration process

* The password recovery process

* Frontend

* The look and feel

* Menus

* Sidebars

*Main Content

*Footer

* Backend

* Content Management

* Add/Edit/Delete

* Security

This will give us a good springboard to delve into more complex functionality.

The aesthetic I have in mind will be barebones at first with clean CSS practices (this will make life a whole lot easier when we have to make changes down the line!).

## Challenge :

Plan out your own CMS, think about the user interface and design choices you’d like to implement, and create a phased approach.

## Conclusion

I hope this tutorial encouraged you to think about security and understand one of the most common exploits. During the course of this series, you will receive the tools necessary to beef up security while maintaining your sanity!

#### Next up

##### CodeWithMe – Let’s go templating.

1423 views · 2 months ago

![](https://images.ctfassets.net/vzl5fkwyme3u/2onKLFlXK4GStdtncTzZiT/9b0b6c5c45bacad4b107264875514180/codewithme.png)

It took me quite some time to settle on my first blog post in this series and I found myself thinking about the most requested functionality in my career – The good ‘ol Custom CMS – typically geared towards clients that want a straight forward, secure solution that can be expanded upon in a modular format and that’s their IP.

This will be our starting point. A blank slate to build something epic with clean code and even cleaner design. And in the spirit of building from scratch, I will refrain from using classes or a framework. The main reasoning behind this is to truly get everyone acquainted with and excited about PHP development.

Join me as I transform rudimentary code into something extraordinary that can be morphed into just about any Content, PHP, and MySQL driven project. So without further ado, let’s jump into it!

### The bare necessities

If you’re just getting started with development, there’s a nifty bite sized server called [UniformServer](https://www.uniformserver.com/) that will be your best friend throughout your coding career. [PHPMyAdmin](https://www.phpmyadmin.net/) (an awesome visual db management tool) comes built in so if you’re looking for a work right out of the box solution, this is it.

Alternatively, you can opt for [XAMPP](https://www.apachefriends.org/index.html) or use an alternative server of your choice.

### Now here’s where the exciting stuff begins, mapping things out.

I don’t see this done/encouraged often enough. Feel free to grab a piece of paper to logically map out your steps or produce a rough draft of where you’d like this project to go.

In this tutorial, I would like to achieve the following:

![](https://cdn.filestackcontent.com/D0KhE3hEQbClPDYqChUm)

### DB, DB, Set up your DB.

This requires a bit of planning but let’s start of with the basic structure we need to see this through.

We are going to need a user table and a content table and are a few ways to tackle this.

If you’re using the PHPMyAdmin tool you can create your database, add user permissions (Click on Permissions after creating your database), and create a table with ease.

![](https://cdn.filestackcontent.com/PiEKcelYTFitGkAOuHhf)

If you’re like me and prefer to look at good ‘ol SQL then writing an SQL statement is the preferred approach.

```

CREATE TABLE `mydbname`.`content` ( `ID` INT(11) NOT NULL AUTO_INCREMENT , `title` VARCHAR(100) NOT NULL , `content` LONGTEXT NOT NULL , `author` VARCHAR(50) NOT NULL , PRIMARY KEY (`ID`)) ENGINE = MyISAM COMMENT = 'content table';

```

Understanding the SQL statement

In a nutshell we are creating a table with important fields. Namely:

#########################

ID | Title | Content | Author

#########################

The ID field is our unique identifier.

Now we can move on to the file structure.

### Everything has a place in the file structure game

You can use a structure that speaks to your coding style / memory.

I tend to use the following:

![](https://cdn.filestackcontent.com/ZhJPGlmGQGKYM1WNsipR)

Choose a name for your CMS, which should be placed at the webroot of your localhost/server.

Replicate the folder structure as per the above example.

### Next, we’re going to create a basic connection file.

You can create a `conn.php` file in your root/includes folder.

The connection file will provide crucial information to connect to the database.

Type the following into your `conn.php` file, remember to include your own database credentials.

```

<?php

$letsconnect = new mysqli("localhost","dbuser","dbpass","dbname");

?>

```

### Let’s go to the homepage (index.php)

Create a file called `index.php` at the root of your CMS folder.

I will be adding comments in my code to help you understand what each line does.

Comments are a useful tool for developers to add important notes private to their code.

We need to pull information from the database so it’s imperative that we include our connection file.

```

<?php

include('includes/conn.php');

if ($letsconnect -> connect_errno) { echo "Error " . $letsconnect -> connect_error;

}else{

$getmydata=$letsconnect -> query("SELECT * FROM content");

foreach($getmydata as $mydata){ echo "Title: "; echo $mydata['title']; echo "<br/>"; echo "Content: "; echo $mydata['content']; echo "<br/>"; echo "Author: "; echo $mydata['author']; echo "<br/>"; echo "<br/>";

}

}

$letsconnect -> close();

?>

```

### Let’s get a (very) basic backend up and running

Create a file called `index.php` in your backend folder.

We need to create a basic form to capture our data.

Let’s code some HTML!

```

<html>

<head><title>Backend - Capture Content</title></head>

<body>

<form action="<?php $_SERVER[‘PHP_SELF’];?>" method="post">

<input type="text" name="title" placeholder="Content Title here" required/>

<textarea name="content">Content Here</textarea>

<input type="text" name="author" placeholder="Author" required/>

<input type="submit" value="Save My Data" name="savedata"/>

</form>

</body>

</html>

```

### Next, we need to process the form data.

Type the following just above the ```<form> ``` tag.

```

<?php

if(isset($_POST['savedata'])){

include('../includes/conn.php');

if ($letsconnect->connect_error) {

die("Your Connection failed: " . $letsconnect->connect_error);

}else{

$sql = "INSERT INTO content(title,content,author)VALUES ('".$_POST["title"]."', '".$_POST["content"]."', '".$_POST["author"]."')";

if (mysqli_query($letsconnect, $sql)) {

echo "Your data was saved successfully!";

} else { echo "Error: " . $sql . "" . mysqli_error($letsconnect);

} $letsconnect->close();

}

}

?>

```

> Note, this is a basic MySQL query to insert data. However, before using this in production it's important to add proper escaping and security to prevent SQL injections. This will be covered in the next article.

### Congrats you made it to the end of tutorial 1!

Test out your creation, modify your content, and play around.

Go to your sitename/index.php to see your frontend after capturing data via sitename/backend/index.php

### Next Up:

#codewithme Now With Security, Functionality, and Aesthetics in mind.

### Conclusion

Coding doesn’t have to be daunting and it’s my aim to divide a complex system into bitesized tutorials so you can truly use the knowledge you’ve acquired in your own projects.

3279 views · 1 years ago

![Midwest PHP and Nomad PHP Join Forces!](https://tessakriesel.com/wp-content/uploads/midwest-php.png)

### [Interested in sponsoring? Check out the prospectus](https://drive.google.com/file/d/1ZYDi9dKCI47caU9vr69dvdhH0Enm2XcM/view)

### A little history

Several years ago I had the distinct privilege of founding Midwest PHP with Jonathan Sundquist. The goal was simple, to bring an affordable PHP conference to Minnesota and the midwest region.

Midwest PHP was created for one simple reason - there weren't a lot of alternatives, especially affordable ones. At the time, your choices were ZendCon in Silicon Valley, php[tek] in Chicago, or Northeast PHP in Boston. While Northeast PHP formed the blueprint of a community conference - it still required a flight and a costly hotel in Boston. I wanted something where local attendees, college students, and those just beginning in their PHP careers could go to learn, network, and become part of the PHP community.

Shortly after Midwest PHP was formed (originally we were using the name PHPFreeze - until Sundquist told me what a horrible idea it was), Adam Culp launched Sunshine PHP which has become one of the top community focused PHP conferences (but still requires that flight and hotel in Miami). Sundquist and I knew that any reasonable developer would still prefer to attend a conference in a blizzard than enjoy the beautiful Floridian weather (ok, that might not be it, but we still understood the need that existed).

After moving to California for my new job, Jonathan Sundquist continued to run Midwest PHP as more community conferences appeared. With his efforts, and the torch being passed to Mike Willbanks, Midwest PHP celebrated it's seventh consecutive year, becoming the longest continuously running PHP conference (if you go by formed date, if you go by actual conference date Sunshine PHP beats us out by a month).

### A renewed focus

![Developers at Midwest PHP](https://pbs.twimg.com/profile_banners/735022608/1416087272/1500x500)

Because of the incredible work Jonathan and Mike have done, Midwest PHP has stood the test of time - and the peaks and valleys that come with any conference. With the shifts in the PHP community and the sad loss of several community conferences - we realized the need for Midwest PHP is more now than ever, and to meet that need we needed to reimagine the way the conference operated.

We also realized that the best way to make Midwest PHP accessible was to combine forces, creating a seamless partnership between Nomad PHP and Midwest PHP. Through this partnership we're not only able to stream the event to make it more accessible ($19.95/mo), but also expand the conference.

This year, taking place on **April 2-4, 2020 - Midwest PHP will bring together over 800 developers** both in-person and virtually! Making this year truly unique, however, and staying with our purpose of helping new developers be part of the PHP community is a **brand new, FREE, beginner track**. I'm excited to say we will be giving away 200 tickets to those wishing to attend our Beginner or Learn PHP track!!!

We will also work to keep prices as low as possible as we offer our standard PHP tracks (Everyday PHP and PHP Performance & Security) starting at $250/ person, and **a brand new enterprise track** geared at developers facing challenges at unprecedented scale starting at $450/ person.

Last but not least, it is our goal with the help of our sponsors to include the workshop day as part of your ticket price - allowing you to get one day of in-depth training, and two more full days of sessions. On top of this, we're also excited to make the Nomad PHP and Nomad JS video libraries available for Standard and Enterprise attendees, providing over 220 additional virtual sessions on demand!

### For sponsors

Sponsoring a conference is hard. We understand the challenge of gauging ROI, planning travel, and coordinating outreach. With the combined forces of Midwest PHP and Nomad PHP, we're able to offer sponsors unique plans that maximize their investment - while ensuring the funds go back into the event to create an amazing experience for our attendees.

Beyond Midwest PHP's goal to be the largest PHP conference this year - the included Nomad PHP advertising will help you reach a much larger and broader audience, allowing for follow up advertisements and consistent engagement with the PHP community.

### [Interested in sponsoring? Check out the prospectus](https://drive.google.com/file/d/1ZYDi9dKCI47caU9vr69dvdhH0Enm2XcM/view)

### Next steps

For more information, please visit the [Midwest PHP](https://midwestphp.org) website. The venue, call for papers, and additional information will all be posted there soon.

7060 views · 1 years ago

![Securing PHP RESTful APIs using Firebase JWT Library](https://images.ctfassets.net/vzl5fkwyme3u/4oaGx3XTrH7kq4KkQbQPQ6/87f8b47b39e42dfdd93e111aa4f91e9f/AdobeStock_191967596.png?w=1000)

Hello Guys,

In our [Last Blog Post](https://nomadphp.com/blog/69/create-simple-restful-apis-using-php-amp-mysql), we have created restful apis,But not worked on its security and authentication. Login api can be public but after login apis should be authenticate using any secure token. one of them is JWT, So i am providing the Steps for Create and use JWT Token in our already created API.

Now its time To Implement JWT Authentication IN our Api, So these are the steps to implement it in our already created Apis

### Step 1:Install and include Firebase JWT(JSON WEB TOKEN) in our project with following composer command        

``` composer require firebase/php-jwt ```

include the composer installed packages

```

require_once('vendor/autoload.php');

```

use namespace using following:

``` use \Firebase\JWT\JWT; ```

### Step 2: Create a JWT server side using Firebase Jwt Library's encode method in Login action , and return it to Client

Define a private variable named Secret_Key in Class like following:

``` private / / you may change this key ```

Now create a method in your class named generateToken as following:

```

public function generateToken($UiD)

{

$payload = array(

'iss' => $_SERVER['HOST_NAME'],

'exp' => time()+600, / / token expiry time in timestamp We have used current we have used 10 minutes as expiry time

'uId' => $UiD

);

try{

$jwt = JWT::encode($payload, $this->Secret_Key,'HS256'); / / last parameter is the Engryption Algorithm name

$res=array("status"=>true,"Token"=>$jwt);

}catch (UnexpectedValueException $e) {

$res=array("status"=>false,"Error"=>$e->getMessage());

}

return $res;

}

```

In our login action , if the user has been logged in successfully then with the status,_data_ and message just replace the login success code with following code:

```

$return['status']=1;

$return['_data_']=$UserData[0];

$return['message']='User Logged in Successfully.';

/ / generate and add jWT token using following method we created in class / /

$jwt=$obj->generateToken($UserData[0]['id']);

if($jwt['status']==true)

{

/ / if token generated successfully then add token in JWT key in response

$return['JWT']=$jwt['Token'];

}

else{

/ / if token generation failed then unset the return user data and add false status

unset($return['_data_']);

$return['status']=0;

$return['message']='Error:'.$jwt['Error'];

}

/ / generate and add jWT token using following method we created in class / /

```

### Step 3: Now with every request after login should have the JWT token in its Post(even we can receive it in get or authentication header also but here we are receiving it in post)

No afetr successfully login you will get the JWt Token in your response,Just add that Token with every post request of after login api calls. So we will do it using postman, Find the screenshot 1 for checking the JWT Token is coming in login api response

![JWT DEMO LOGIN API RESPONSE](https://www.w3school.info/blogimages/JWT_LOGIN_API.png)

### Step 4:After reciving the JWt in every after login api call, we need to check whether the token is fine using JWT decode method in After login Apis like ```UserBlogs``` is a After login Api, So for verify that we are creating Authencate method in class like following:

```

public function Authenticate($JWT,$Curret_User_id)

{

try {

$decoded = JWT::decode($JWT,$this->Secret_Key, array('HS256'));

$payload = json_decode(json_encode($decoded),true);

if($payload['uId'] == $Curret_User_id) / / verify that the user id coming in after login api is equals to the decoded payload user id, if matched then the token is fine and data not tempered

{

$res=array("status"=>true);

}else{

$res=array("status"=>false,"Error"=>"Invalid Token or Token Exipred, So Please login Again!");

}

}catch (UnexpectedValueException $e) {

$res=array("status"=>false,"Error"=>$e->getMessage());

}

return $res;

}

```

### Step 5: Cross check the response returned by Authenticate method in ```UserBlogs``` Action of api , replace the ```UserBlogs``` Action inner content with following code:

```

if(isset($_POST['Uid']))

{

/ / Authenticate the JWT before fetching the data

$resp=$obj->Authenticate($_POST['JWT'],$_POST['Uid']);

if($resp['status']==false)

{

$return['status']=0;

$return['message']='Error:'.$resp['Error'];

}

/ / Authenticate the JWT before fetching the data

else{

$blogs=$obj->get_all_blogs($_POST['Uid']);

if(count($blogs)>0)

{

$return['status']=1;

$return['_data_']=$blogs;

$return['message']='Success.';

}

else

{

$return['status']=0;

$return['message']='Error:Invalid UserId!';

}

}

}

else

{

$return['status']=0;

$return['message']='Error:User Id not provided!';

}

```

Ah great its time to check out the UserBlogs Api, please find the screenshoot for that, Remember we need to put the JWt Token in POST Parameter as we have already recived that Value in Login Api call.

![JWT DEMO Authentication in userBlogs API Call](https://www.w3school.info/blogimages/JWT_userBlogs_API.png)

Now if you want to verify that token is expiring in given time(10 minutes after generation time/login time), i am just clicking the same api with same token after 10 minutes and you can see there will not return any data and it is returning status false with following message :

![JWT DEMO Authentication in userBlogs API Call](https://www.w3school.info/blogimages/JWT_userBlogs_API_TOKEN_EXPIRY.png)

Also if you want to eloborate it more then i suggest you to try with modify Uid value with same token , you will another authentication issue and also if you modify the JWT token also then also you will not get the desired result and get authentication Issue

Thanks for reading out if you want the complete code of this file then please find following:

```

<?php

header("Content-Type: application/json; charset=UTF-8");

require_once('vendor/autoload.php');

use \Firebase\JWT\JWT;

class DBClass {

private $host = "localhost";

private $username = "root";

private $password = ""; / / set your passwrd here

private $database = "news";

public $connection;

private $Secret_Key="*$%43MVKJTKMN$#"; / / you may change this key

/ / get the database connection

public function connect(){

$this->connection = null;

try{

$this->connection = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->database, $this->username, $this->password);

$this->connection->exec("set names utf8");

}catch(PDOException $exception){

echo "Error: " . $exception->getMessage();

}

return $this->connection;

}

public function login($email,$password){

if($this->connection==null)

{

$this->connect();

}

$query = "SELECT id,name,email,createdAt,updatedAt from users where email= ? and password= ?";

$stmt = $this->connection->prepare($query);

$stmt->execute(array($email,md5($password)));

$ret= $stmt->fetchAll(PDO::FETCH_ASSOC);

return $ret;

}

public function get_all_blogs($Uid){

if($this->connection==null)

{

$this->connect();

}

$query = "SELECT b.*,u.id as Uid,u.email as Uemail,u.name as Uname from blogs b join users u on u.id=b.user_id where b.user_id= ?";

$stmt = $this->connection->prepare($query);

$stmt->execute(array($Uid));

$ret= $stmt->fetchAll(PDO::FETCH_ASSOC);

return $ret;

}

public function response($array)

{

echo json_encode($array);

exit;

}

public function generateToken($UiD)

{

$payload = array(

'iss' => $_SERVER['HOST_NAME'],

'exp' => time()+600, / / token expiry time in timestamp We have used current we have used 10 minutes as expiry time

'uId' => $UiD

);

try{

$jwt = JWT::encode($payload, $this->Secret_Key,'HS256'); / / last parameter is the Engryption Algorithm name

$res=array("status"=>true,"Token"=>$jwt);

}catch (UnexpectedValueException $e) {

$res=array("status"=>false,"Error"=>$e->getMessage());

}

return $res;

}

public function Authenticate($JWT,$Current_User_id)

{

try {

$decoded = JWT::decode($JWT,$this->Secret_Key, array('HS256'));

$payload = json_decode(json_encode($decoded),true);

if($payload['uId'] == $Current_User_id) / / verify that the user id coming in after login api is equals to the decoded payload user id, if matched then the token is fine and data not tempered

{

$res=array("status"=>true);

}else{

$res=array("status"=>false,"Error"=>"Invalid Token or Token Exipred, So Please login Again!");

}

}catch (UnexpectedValueException $e) {

$res=array("status"=>false,"Error"=>$e->getMessage());

}

return $res;

}

}

/ / receive the requests here / /

$return=array();

$obj = new DBClass();

if(isset($_GET['action']) && $_GET['action']!='')

{

if($_GET['action']=="login")

{

if(isset($_POST['email']) && isset($_POST['password']))

{

$UserData=$obj->login($_POST['email'],$_POST['password']);

if(count($UserData)>0)

{

$return['status']=1;

$return['_data_']=$UserData[0];

$return['message']='User Logged in Successfully.';

/ / generate and add jWT token using following method we created in class / /

$jwt=$obj->generateToken($UserData[0]['id']);

if($jwt['status']==true)

{

/ / if token generated successfully then add token in JWT key in response

$return['JWT']=$jwt['Token'];

}

else{

/ / if token generation failed then unset the return user data and add false status

unset($return['_data_']);

$return['status']=0;

$return['message']='Error:'.$jwt['Error'];

}

/ / generate and add jWT token using following method we created in class / /

}

else

{

$return['status']=0;

$return['message']='Error:Invalid Email or Password!';

}

}

else

{

$return['status']=0;

$return['message']='Error:Email or Password not provided!';

}

}

elseif($_GET['action']=="UserBlogs")

{

if(isset($_POST['Uid']))

{

/ / Authenticate the JWT before fetching the data

$resp=$obj->Authenticate($_POST['JWT'],$_POST['Uid']);

if($resp['status']==false)

{

$return['status']=0;

$return['message']='Error:'.$resp['Error'];

}

/ / Authenticate the JWT before fetching the data

else{

$blogs=$obj->get_all_blogs($_POST['Uid']);

if(count($blogs)>0)

{

$return['status']=1;

$return['_data_']=$blogs;

$return['message']='Success.';

}

else

{

$return['status']=0;

$return['message']='Error:Invalid UserId!';

}

}

}

else

{

$return['status']=0;

$return['message']='Error:User Id not provided!';

}

}

}

else

{

$return['status']=0;

$return['message']='Error:Action not provided!';

}

$obj->response($return);

$obj->connection=null;

?>

```

SPONSORS

Faster PHP Cloud Hosting