In this tutorial, you will learn how to Implement The JWT (JSON Web Token) with PHP.

What is JWT (JSON Web Token)?


Implementing The JWT (JSON Web Token) with PHP

Download JWT for PHP

First, you need to download or clone JWT from https://github.com/firebase/php-jwt.

Or you can install this PHP-JWT package using Composer. To do this run the following command –

composer require firebase/php-jwt

After downloading the PHP-JWT ZIP file, extract this ZIP file.

Now inside the PHP-JWT folder, you can see some files and folders, but we don’t need all the files and folders, we only need the src folder.

So, copy the src folder and go to your localhost www directory or the htdocs folder, and here, create a new folder called php_jwt and then paste the src folder inside the php_jwt folder.


After completing the above steps, Now we need to create some files. But before going further let’s take a look at your php_jwt folder structure.

php_jwt folder structure

First, we will create the JwtHandler.php file. Basically this is a class where we handle all the JWT actions like encoding and decoding token.

<?php
require './src/JWT.php';
require './src/ExpiredException.php';
require './src/SignatureInvalidException.php';
require './src/BeforeValidException.php';

use \Firebase\JWT\JWT;

class JwtHandler {
    protected $jwt_secrect;
    protected $token;
    protected $issuedAt;
    protected $expire;
    protected $jwt;

    public function __construct()
    {
        // set your default time-zone
        date_default_timezone_set('Asia/Kolkata');
        $this->issuedAt = time();
        
        // Token Validity (3600 second = 1hr)
        $this->expire = $this->issuedAt + 3600;

        // Set your secret or signature
        $this->jwt_secrect = "this_is_my_secrect";  
    }

    // ENCODING THE TOKEN
    public function _jwt_encode_data($iss,$data){

        $this->token = array(
            //Adding the identifier to the token (who issue the token)
            "iss" => $iss,
            "aud" => $iss,
            // Adding the current timestamp to the token, for identifying that when the token was issued.
            "iat" => $this->issuedAt,
            // Token expiration
            "exp" => $this->expire,
            // Payload
            "data"=> $data
        );

        $this->jwt = JWT::encode($this->token, $this->jwt_secrect);
        return $this->jwt;

    }
    
    //DECODING THE TOKEN
    public function _jwt_decode_data($jwt_token){
        try{
            $decode = JWT::decode($jwt_token, $this->jwt_secrect, array('HS256'));
            return $decode->data;
        }
        catch(\Firebase\JWT\ExpiredException $e){
            return $e->getMessage();
        }
        catch(\Firebase\JWT\SignatureInvalidException $e){
            return $e->getMessage();
        }
        catch(\Firebase\JWT\BeforeValidException $e){
            return $e->getMessage();
        }
        catch(\DomainException $e){
            return $e->getMessage();
        }
        catch(\InvalidArgumentException $e){
            return $e->getMessage();
        }
        catch(\UnexpectedValueException $e){
            return $e->getMessage();
        }

    }
}

Creating / Encoding JWT Tokens

<?php
require 'JwtHandler.php';
$jwt = new JwtHandler();

$token = $jwt->_jwt_encode_data(
    'http://localhost/php_jwt/',
    array("email"=>"[email protected]","id"=>21)
);

echo "<strong>Your Token is -</strong><br> $token";

Now open the URL on your browser – http://localhost/php_jwt/index.php

Browser Output
Your Token is –
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3RcL3BocF9qd3RcLyIsImF1ZCI6Imh0dHA6XC9cL2xvY2FsaG9zdFwvcGhwX2p3dFwvIiwiaWF0IjoxNTczMzcxNjQyLCJleHAiOjE1NzMzNzUyNDIsImRhdGEiOnsiZW1haWwiOiJqb2huQGVtYWlsLmNvbSIsImlkIjoyMX19.1d131L2PezRNz1X6356l5TYtLlvRdSsYFNFCTiR2w3s

Copy this token.


Decoding JWT Tokens

<?php
if(isset($_GET['token'])){
    require 'JwtHandler.php';
    $jwt = new JwtHandler();

    $data =  $jwt->_jwt_decode_data(trim($_GET['token']));

    var_dump($data);

    echo "<br><hr>";
}
?>
<form action="" method="GET">
    <label for="_token"><strong>Enter Token</strong></label>
    <input type="text" name="token" id="_token">
    <input type="submit" value="Docode">
</form>

Now open this URL on your Browser – http://localhost/php_jwt/decode.php and paste the token into the input box and then click on the decode button.

Browser Output
object(stdClass)#4 (2) {
  ["email"]=>
  string(14) "[email protected]"
  ["id"]=>
  int(21)
}

The token will expire after 1 hour because we have set the token expire-time to 1hr.

Leave a Reply

Your email address will not be published. Required fields are marked *