How to Generate JWT Token in PHP ?
Step 1: Install the Firebase JWT Library
The most popular library for handling JWTs in PHP is firebase/php-jwt.
Install it using Composer:
composer require firebase/php-jwt
If you’re not using Composer, you can download the library manually.
Step 2: Create a JWT Token
<?php
require 'vendor/autoload.php';
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
// Define the payload
$payload = [
'iss' => 'your-website.com', // Issuer
'aud' => 'your-client.com', // Audience
'iat' => time(), // Issued at
'exp' => time() + 3600, // Expires in 1 hour
'sub' => 'user_id_123', // Subject (user ID or similar)
'name' => 'John Doe' // Custom data
];
// Define a secret key
$secretKey = 'your-256-bit-secret';
// Encode the payload to create JWT
$jwt = JWT::encode($payload, $secretKey, 'HS256');
echo "Generated JWT:\n" . $jwt;
Step 3: Decode and Verify the Token
You can later verify and decode the token like this:
$decode = JWT::decode($jwt, new Key($secretKey, 'HS256'));
print_r($decode);
This helps you extract the original data and verify the token hasn’t been tampered with.