Lear to use Firebase JWT with PHP

How to use Firebase JWT with PHP?

Here you will learn how to Implement or use the Firebase JWT (JSON Web Token) with PHP.

Example of using Firebase JWT with PHP

First, start your localhost then go to the htdocs or www directory, and then create a new folder called php-jwt (You can name this folder whatever you want).

Installing the Firebase JWT

After that, inside the php-jwt folder install the Firebase JWT via Composer.

composer require firebase/php-jwt
Installing Firebase JWT via composer

After successfully installing firebase/php-jwt, you can see that the vendor folder and composer.json file has been generated.

PHP JWT folder structure
{
    "require": {
        "firebase/php-jwt": "^6.8"
    }
}

Using the Firebase PHP-JWT

  • JwtHandler.php” – JwtHandler class has two methods encode() and decode() that generates and decodes tokens with the help of Firebase\JWT.
  • generate_token.php” – Generate a new token using encode() method of JwtHandler class.
  • decode_token.php” – Decode the generated token using decode() method of the JwtHandler Class.
<?php
require __DIR__ . "/vendor/autoload.php";

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JwtHandler
{
    protected $secrect;
    protected $issuedAt;
    protected $expire;

    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 strong secret or signature
        $this->secrect = "this_is_my_secrect";
    }

    public function encode($iss, $data)
    {

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

        return JWT::encode($token, $this->secrect, 'HS256');
    }

    public function decode($token)
    {
        try {
            $decode = JWT::decode($token, new Key($this->secrect, 'HS256'));
            return $decode->data;
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
}
<?php
require __DIR__ . "/JWTHandler.php";

$jwt = new JwtHandler();

//Payload can be anything you want to store in the token
$payload = "Hi this is Rahul";

$token = $jwt->encode("http://localhost/php-jwt/", $payload);

echo "$token";
<?php
require __DIR__ . "/JWTHandler.php";

//Add your token which you have generated
$token = "";

$jwt = new JwtHandler();
$data =  $jwt->decode($token);
var_dump($data);
PHP JWT token testing