DevToolsForYou

JWT Encoder and Decoder in PHP — Code Examples

JWT Encoder and Decoder in PHPUse the online tool →

JSON Web Tokens (JWTs) are a compact, URL-safe format for transmitting claims between parties. A JWT has three Base64url-encoded parts separated by dots: header, payload, and signature. Here is how to sign, verify, and decode JWTs in each language.

firebase/php-jwt is the standard PHP JWT library. Use JWT::encode to sign and JWT::decode with a Key object to verify.

PHP
<?php
// composer require firebase/php-jwt
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$secret = "my-secret-key";
$payload = [
    "user_id" => 42,
    "name"    => "Alice",
    "role"    => "admin",
    "iat"     => time(),
    "exp"     => time() + 3600,
];

// Sign (encode)
$token = JWT::encode($payload, $secret, "HS256");
echo $token . "\n";
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

// Verify and decode
try {
    $decoded = JWT::decode($token, new Key($secret, "HS256"));
    echo $decoded->name . "\n"; // Alice
    echo $decoded->user_id . "\n"; // 42
} catch (\Firebase\JWT\ExpiredException $e) {
    echo "Token expired\n";
} catch (\Exception $e) {
    echo "Invalid token: " . $e->getMessage() . "\n";
}
Notes & gotchas
  • JWT::decode returns a stdClass object, not an array — use -> to access properties.
  • Pass the algorithm explicitly in the Key constructor to prevent algorithm confusion attacks.
  • For RS256, pass the private key PEM string to JWT::encode and the public key PEM to JWT::decode.
Try it in your browser

Need to jwt encode/decode without writing code? The JWT Encoder and Decoder runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open JWT Encode/Decode
JWT Encoder and Decoder in other languages