SyntaxStudy
Sign Up
PHP JSON Web Tokens (JWT) in PHP
PHP Advanced 6 min read

JSON Web Tokens (JWT) in PHP

JSON Web Tokens

JWT encodes claims as a Base64URL-encoded JSON payload signed with a secret. Use the firebase/php-jwt library for creating and verifying tokens.

Example
<?php
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$secret = "your-secret-key";

// Create token
$payload = [
    "sub"  => $userId,
    "name" => $userName,
    "iat"  => time(),
    "exp"  => time() + 3600, // expires in 1 hour
];
$token = JWT::encode($payload, $secret, "HS256");

// Verify and decode token
try {
    $decoded = JWT::decode($token, new Key($secret, "HS256"));
    echo $decoded->name; // userName
} catch (\Exception $e) {
    http_response_code(401);
    echo json_encode(["error" => "Invalid token"]);
}
Pro Tip

Never store JWTs in localStorage — use HttpOnly cookies to protect them from XSS attacks.