Implement JWT(JSON Web Token) in PHP

CONFIG FILE
<?php

return [
    "jwt_secret" => "This is secret key",
];







ENCODE Data File
<?php

require_once "vendor/autoload.php";

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

$config = require_once "config.php";

$secret_key = $config["jwt_secret"];

$payload = array(
    "iss" => "sharmacoder",
    "iat" => time(),
    "exp" => strtotime("+1 hour"),
    "email" => "sharma@gmail.com"
);

$jwt = JWT::encode($payload, $secret_key, "HS256");

echo "JWT : " . $jwt;








DECODE Data File
<?php

require_once "vendor/autoload.php";

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

$config = require_once "config.php";

$secret_key = $config["jwt_secret"];

$headers = apache_request_headers();

if (isset($headers["Authorization"])) {
    $authorizationHeader = $headers["Authorization"];
    //print_r($authorizationHeader);
    $headerValue = explode(" ", $authorizationHeader);

    $jwt = $headerValue[1];
    try {
        $decoded = JWT::decode($jwt, new Key($secret_key, "HS256"));
        print_r($decoded);
    } catch (Exception $e) {
        echo "Error : " . $e->getMessage();
    }
} else {
    echo "No Authorization header is present<br><br>";
}

$data = [
    "name" => "My secure product",
    "code" => "6594"
];
print_r($data);




 

Comments

Popular posts from this blog

Logical_Operators

SubQuery with EXISTS and NOT EXISTS in PHP

Get Functions