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.
JWT encodes claims as a Base64URL-encoded JSON payload signed with a secret. Use the firebase/php-jwt library for creating and verifying tokens.
<?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"]);
}
Never store JWTs in localStorage — use HttpOnly cookies to protect them from XSS attacks.