How to Implement the JWT with PHP?

In this tutorial, you will learn how to implement or use the JWT (JSON Web Token) with PHP.

First, start your localhost then go to the htdocs or www directory, and here create a new folder called php-jwt.

After that, you need to download the JWT inside this folder to use the JWT.

You can clone the JWT from Github or you can download it via Composer.

composer require firebase/php-jwt

After completing the setup of JWT, we will create three files inside the php-jwt folder –

php-jwt/
├─ JwtHandler.php
├─ index.php
├─ decode.php

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

<?php

/** If you have cloned the JWT from Github,
 * include it in the following way, and remove the require autoload.php
 * require './php-jwt/src/JWT.php';
 */

require './vendor/autoload.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";
    }

    public function jwtEncodeData($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, 'HS256');
        return $this->jwt;
    }

    public function jwtDecodeData($jwt_token)
    {
        try {
            $decode = JWT::decode($jwt_token, $this->jwt_secrect, array('HS256'));
            return $decode->data;
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
}

Testing part

In the index.php, JwtHandler class has been used to create authorization tokens.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP JWT</title>
    <style>
        div {
            max-width: 600px;
            word-wrap: break-word;
            padding: 5px;
            background: #f5f5f5;
            border: 1px solid #999999;
        }
    </style>
</head>

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

    $token = $jwt->jwtEncodeData(
        'http://localhost/php-jwt/',
        array("name" => "John", "email" => "[email protected]", "id" => 21)
    );

    echo "<strong>Your Token is -</strong><br><div><code>$token</code></div>";
    ?>
</body>

</html>
PHP JWT encode token
PHP JWT index.php

And finally, we will create decode.php to decode the encoded authorization token.

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

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

    if(isset($data->id) && isset($data->name) && isset($data->email)):
        echo "<ul>
        <li>ID => $data->id</li>
        <li>Name => $data->name</li>
        <li>Email => $data->email</li>
        </ul>";
    else:
        print_r($data);
    endif;
}
?>
<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>
PHP JWT decode authorization token

2 Comments

  1. HI, thanks for the information. Your way of coding is much more understandable than github information. Can you please leave information about how can web implement RS256 with JWTHandler?

    Thank you, I appriciate your help.

Leave a Reply

Your email address will not be published.