PHP & Web Development Blogs

Showing 1 to 5 of 47 blog articles.
17158 views · 1 years ago

![Creating a URL shortener application in PHP & MySQL](https://images.ctfassets.net/vzl5fkwyme3u/3OjKfmylv2k8eWayqeCUWG/6d8e996fc7c757135df7fdd322fd50a4/AdobeStock_65694631.jpeg?w=1000)

Hi Guys,

In this post we will learn how to create your URL shortening application in PHP and MySQL.

You may also use this app as an API by calling the URLs from another application.

## Step 1: Creating a Table

```mysql

CREATE TABLE IF NOT EXISTS `url_shorten` (

`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,

`url` tinytext NOT NULL,

`short_code` varchar(50) NOT NULL,

`hits` int(11) NOT NULL,

`added_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP

) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

```

## Step 2: Create a file `index.php` and add database credentials in it

```php

$servername = 'localhost';

$username = 'root';

$password = ''; / /on localhost by default there is no password

$dbname = 'shorten_db';

$base_url='http://localhost/myapp/'; / / it is your application url

```

## Step 3: Get the URL in querystring and return a shortened URL using following code:

```php

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

{

$url=urldecode($_GET['url']);

if (filter_var($url, FILTER_VALIDATE_URL))

{

/ / Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

/ / Check connection

if ($conn->connect_error) {

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

}

$slug=GetShortUrl($url);

$conn->close();

echo $base_url.$slug;

}

else

{

die("$url is not a valid URL");

}

}

else

{ / /show the basic html form having element url

?>

<center>

<h1>Put Your Url Here</h1>

<form>

<p><input style="width:500px" type="url" name="url" required /></p>

<p><input type="submit" /></p>

</form>

</center>

<?php

}

```

Now we'll create a function called `GetShortUrl` for creating the short URL:

```php

function GetShortUrl($url){

global $conn;

$query = "SELECT * FROM url_shorten WHERE url = '".$url."' ";

$result = $conn->query($query);

if ($result->num_rows > 0) {

$row = $result->fetch_assoc();

return $row['short_code'];

} else {

$short_code = generateUniqueID();

$sql = "INSERT INTO url_shorten (url, short_code, hits)

VALUES ('".$url."', '".$short_code."', '0')";

if ($conn->query($sql) === TRUE) {

return $short_code;

} else {

die("Unknown Error Occured");

}

}

}

```

The above function is using the `generateUniqueID()` function to generate a unique id for long urls. We can generate and retrieve the unique ID like so:

```php

function generateUniqueID(){

global $conn;

$token = substr(md5(uniqid(rand(), true)),0,6); / / creates a 6 digit unique short id

$query = "SELECT * FROM url_shorten WHERE short_code = '".$token."' ";

$result = $conn->query($query);

if ($result->num_rows > 0) {

generateUniqueID();

} else {

return $token;

}

}

```

## Step 4

Now your code is ready to generate a unique short code for long URLs, but we still need to setup the redirection. When redirecting it should also increase a pageview/ hits in the table and then redirect to the longer, original URL.

Here is the code that allows us to do this:

```php

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

{

$slug=urldecode($_GET['redirect']);

/ / Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

/ / Check connection

if ($conn->connect_error) {

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

}

$url= GetRedirectUrl($slug);

$conn->close();

header("location:".$url);

exit;

}

```

This code uses a function called `GetRedirectUrl()` that we need to define, like so:

```php

function GetRedirectUrl($slug){

global $conn;

$query = "SELECT * FROM url_shorten WHERE short_code = '".addslashes($slug)."' ";

$result = $conn->query($query);

if ($result->num_rows > 0) {

$row = $result->fetch_assoc();

/ / increase the hit

$hits=$row['hits']+1;

$sql = "update url_shorten set hits='".$hits."' where id='".$row['id']."' ";

$conn->query($sql);

return $row['url'];

}

else

{

die("Invalid Link!");

}

}

```

## Step 5

You are almost done now! If you don't want to use the redirect parameter in url for redirection purpose you will need to create a `.htaccess` file in your project and add following code:

```php

RewriteEngine on

RewriteRule ^([a-z0-9]{6})$ index.php?redirect=$1 [L]

```

### And You Have done it!

Now if you want to convert any url to short url just pass the url in get param of index.php like following:

http://localhost/myapp/?url=http://www.google.com **or** http://localhost/myapp/index.php?url=http://www.google.com **or** just open http://localhost/myapp/ **or** http://localhost/myapp/index.php,

It will show a html form where you may input any URL and click submit.

After submitting form or hitting the url with param url then it will print a shortened URL on screen. You may use that URL in new tab and see the url will be redirect to long URL and increase a Hit/ Pageview in MySQL table.

## Please find the full code for index.php here:

```php

<?php

$servername = 'localhost';

$username = 'root';

$password = ''; / / on localhost by default there is no password

$dbname = 'shorten_db';

$base_url='http://localhost/myapp/'; / / it is your application url

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

{

$url=urldecode($_GET['url']);

if (filter_var($url, FILTER_VALIDATE_URL))

{

/ / Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

/ / Check connection

if ($conn->connect_error) {

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

}

$slug=GetShortUrl($url);

$conn->close();

echo $base_url.$slug;

}

else

{

die("$url is not a valid URL");

}

}

else

{

?>

<center>

<h1>Put Your Url Here</h1>

<form>

<p><input style="width:500px" type="url" name="url" required /></p>

<p><input type="submit" /></p>

</form>

</center>

<?php

}

function GetShortUrl($url){

global $conn;

$query = "SELECT * FROM url_shorten WHERE url = '".$url."' ";

$result = $conn->query($query);

if ($result->num_rows > 0) {

$row = $result->fetch_assoc();

return $row['short_code'];

} else {

$short_code = generateUniqueID();

$sql = "INSERT INTO url_shorten (url, short_code, hits)

VALUES ('".$url."', '".$short_code."', '0')";

if ($conn->query($sql) === TRUE) {

return $short_code;

} else {

die("Unknown Error Occured");

}

}

}

function generateUniqueID(){

global $conn;

$token = substr(md5(uniqid(rand(), true)),0,6); / / creates a 6 digit unique short id

$query = "SELECT * FROM url_shorten WHERE short_code = '".$token."' ";

$result = $conn->query($query);

if ($result->num_rows > 0) {

generateUniqueID();

} else {

return $token;

}

}

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

{

$slug=urldecode($_GET['redirect']);

/ / Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

/ / Check connection

if ($conn->connect_error) {

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

}

$url= GetRedirectUrl($slug);

$conn->close();

header("location:".$url);

exit;

}

function GetRedirectUrl($slug){

global $conn;

$query = "SELECT * FROM url_shorten WHERE short_code = '".addslashes($slug)."' ";

$result = $conn->query($query);

if ($result->num_rows > 0) {

$row = $result->fetch_assoc();

/ / increase the hit

$hits=$row['hits']+1;

$sql = "update url_shorten set hits='".$hits."' where id='".$row['id']."' ";

$conn->query($sql);

return $row['url'];

}

else

{

die("Invalid Link!");

}

}

```

12315 views · 1 years ago

![Generate PDF from HTML in Laravel 5.7](https://images.ctfassets.net/vzl5fkwyme3u/7BjL7ILSA84wgAUIo2K2yg/43ac850a592f4a272e910c30e06b97ba/AdobeStock_39841236.jpeg?w=1000)

Today, I will share with you how to create a PDF file from HTML blade file in Laravel 5.7. We will be using `dompdf` package for generating the PDF file.

In the below example, we will install `barryvdh/laravel-dompdf` using composer package and thereafter we will add new route url with controller. Then we will create a blade file. Then after we have to just run project with serve and we can check the PDF file is for download.

## Download Laravel 5.7

Now I am going to explain the step by step from scratch with laravel installation for `dompdf`. To get started, we need to download fresh Laravel 5.7 application using command, so open our terminal and run the below command in the command prompt:

```php

composer create-project --prefer-dist laravel/laravel blog

```

## Install laravel-dompdf Package

Now we will install barryvdh/laravel-dompdf composer package by using the following composer command in ourLlaravel 5.7 application.

```php

composer require barryvdh/laravel-dompdf

```

Then the package is successfully installed in our application, after that open config/app.php file and we need to add alias and service provider.

**config/app.php**

```php

'providers' => [

....

Barryvdh\DomPDF\ServiceProvider::class,

],

'aliases' => [

....

'PDF' => Barryvdh\DomPDF\Facade::class,

]

```

## Create Routes

Now we need to create routes for the items listing. so now open our "routes/web.php" file and we need to add following route.

**routes/web.php**

```php

Route::get('demo-generate-pdf','[email protected]');

```

## Create Controller

Here,we need to create a new controller *HomeController* (mostly it will be there, we can skip this step if we don't need to create a controller) that will manage our pdf generation using the `generatePDF()` method of route.

**app/Http/Controllers/HomeController.php**

```php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use PDF;

class HomeController extends Controller

{

public function demoGeneratePDF()

{

$data = ['title' => 'Welcome to My Blog'];

$pdf = PDF::loadView('myPDF', $data);

return $pdf->download('demo.pdf');

}

}

```

## Create Blade File

In the final step, let us create demoPDF.blade.php in the resources/views/demoPDF.blade.php for structure of pdf file and add the following code:

**resources/views/demoPDF.blade.php**

```html

<!DOCTYPE html>

<html>

<head>

<title>Hi</title>

</head>

<body>

<h1>Welcome to My BLOG - {{ $title }}</h1>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod

tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,

quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo

consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse

cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non

proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

</body>

</html>

```

Now run the below command for serve and test it:

```curl

php artisan serve

```

9470 views · 2 years ago

![Install Composer for PHP](https://images.ctfassets.net/vzl5fkwyme3u/6REkTRobXqOMgyiyCa8ioS/fb4fc03a6a5514df3522a605b981505b/composer.png?w=1000)

Composer is a must-have tool for every PHP developer these days. This page is a simple breakdown of quick-install instructions.

## How do I install composer?

1. Use PHP to download the composer installer, place it in the current directory, and name it `composer-setup.php`

2. Use PHP to check the hash of the file you downloaded and compare it to the known value of the hash. You can always find the current value of the hash for the installer on the [Composer Public Keys / Signatures](https://composer.github.io/pubkeys.html) page.

3. Run the setup program to install composer. This does more than just download the latest copy of composer, it also sets up your local ~/.composer directory. This will install composer into the current directory. You can add the --install-dir=DIR to specify where you want composer installed. You can also specify --filename=composer to change the installed filename. You can use anything you like that doesn’t already exist in your specified directory, you don’t have to use the name composer. This is a great way to get rid of the .phar at the end of the name if you don’t like it.

4. Use PHP to remove the installer from the current directory.

**To install composer for PHP you use PHP to download the installer, set a few options, and then actually perform the install.**

```php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"```

```php -r "if (hash_file('SHA384', 'composer-setup.php') === '55d6ead61b29c7bdee5cccfb50076874187bd9f21f65d8991d46ec5cc90518f447387fb9f76ebae1fbbacf329e583e30') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"```

```php composer-setup.php```

```php -r "unlink('composer-setup.php');"```

Below is a version you can copy ‘n paste.

Breakdown:

## Recommended Setup for Linux and macOS:

```

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

php -r "if (hash_file('SHA384', 'composer-setup.php') === '55d6ead61b29c7bdee5cccfb50076874187bd9f21f65d8991d46ec5cc90518f447387fb9f76ebae1fbbacf329e583e30') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

php composer-setup.php --install-dir=/usr/local/bin --filename=composer

php -r "unlink('composer-setup.php');"```

**WARNING**: Line two IS WHERE IT compares the hasH of the installer you just downloaded to a hard-coded value. The value specified in the script is the value for the current version of the installer as of this writing. If it fails, check the [Composer Public Keys / Signatures](https://composer.github.io/pubkeys.html) page and get the latest version. Plug it into the script below and try again.

Windows user, change the `--installdir=` to a directory in your path.

## Recommended Setup for Windows

If you are running Microsoft Windows, the instructions above will work for you as long as you use the proper install paths. You can however download ComposerSetup.exe from the [Composer Introduction](https://getcomposer.org/doc/00-intro.md) page. Execute this and it will install composer and set your path so that you can run composer from anywhere. You will have to close your terminal window and open a new one after the install for the path to be updated.

That’s it, you should now have Composer installed.

## Composer installation Resources

* [Composer Homepage](https://getcomposer.org/)

* [Composer Introduction](https://getcomposer.org/doc/00-intro.md)

* [Download Composer](https://getcomposer.org/download/)

* [Composer Public Keys / Signatures](https://composer.github.io/pubkeys.html)

8940 views · 1 years ago

![Create Simple RESTful APIs using PHP & MySQL](https://images.ctfassets.net/vzl5fkwyme3u/5s6X92LpF8dGGVZEnXGRK0/387bfe60541987d308e8201ca5bb5d3f/api_blog_post.png?w=1000)

Hi Guys,

I am sharing you the way to create simple resful apis using php and mysql. We are creating 2 apis here

First is to Loggin a existing user and second is to get list of written blogs by logged in user.

#### Create any database, i am taking ```news``` as the database name here, After it create following 2 tables inside it.

```

CREATE TABLE `users` (

`id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

`name` varchar(100),

`email` varchar(100),

`password` varchar(100),

`createdAt` datetime NOT NULL,

`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

);

CREATE TABLE `blogs` (

`id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

`user_id` int(11),

`title` varchar(255),

`summary` Tinytext,

`body` Text,

`createdAt` datetime NOT NULL,

`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

);

```

#### Now putting some dummy data to read via the api

```

--create 2 entries in users table--

INSERT INTO `news`.`users` (`id`, `name`, `email`, `password`, `createdAt`, `updatedAt`) VALUES (1, 'jeetendra singh', '[email protected]', MD5('123456'), '2018-12-28 02:05:12', CURRENT_TIMESTAMP), (2, 'Manvik Singh chaudhary', '[email protected]', MD5('654321'), '2018-12-28 03:08:11', CURRENT_TIMESTAMP);

-- create 2 blogs by userid 1--

INSERT INTO `news`.`blogs` (`id`, `user_id`, `title`, `summary`, `body`, `createdAt`, `updatedAt`) VALUES (1, '1', 'Blog title 1 by jeetendra', 'Blog summary 1 by jeetendra', 'Blog body 1 by jeetendra', '2018-12-28 02:00:00', CURRENT_TIMESTAMP), (2, '1', 'Blog Title 2 by jeetendra ', 'Blog summary 2 by jeetendra ', 'Blog body 2 by jeetendra ', '2018-12-28 05:10:21', CURRENT_TIMESTAMP);

-- create 2 blogs by userid 2

INSERT INTO `news`.`blogs` (`id`, `user_id`, `title`, `summary`, `body`, `createdAt`, `updatedAt`) VALUES (3, '2', 'Blog title 1 by manvik', 'Blog summary 1 by manvik', 'Blog body 1 by manvik', '2018-12-28 02:00:00', CURRENT_TIMESTAMP), (4, '2', 'Blog Title 2 by manvik ', 'Blog summary 2 by manvik ', 'Blog body 2 by manvik ', '2018-12-28 05:10:21', CURRENT_TIMESTAMP);

```

#### After creating this create a index.php and put this code for Db connection, login and get all blog method

```

<?php

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

class DBClass {

private $host = "localhost";

private $username = "root";

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

private $database = "news";

public $connection;

/ / 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;

}

}

/ /recieve 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.';

}

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']))

{

$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;

?>

```

#### Now api file is set, just make the urls pretty(readable form) using .htaccess file, put following code in it

```

RewriteEngine On

RewriteRule ^api/(.*) index.php?action=$1

```

#### Now your Simple Restful Apis are ready to use, Now Let me show you the postman screenshot where i have used these apis.

**Login Api Call:**

![LOGIN API CALL](https://www.w3school.info/blogimages/login_api.png)

**User Post/Blog Api Call**

![USER BLOGS](https://www.w3school.info/blogimages/UserBlogs_api.png)

8287 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