PHP

Verify a JWT (HS256)

admin by @admin ADMIN
5h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Pair to jwtSign: verify the signature, check the exp claim, and return the decoded payload — or null on any failure. Uses hash_equals for constant-time signature comparison.
PHP
Raw
<?php
function jwtVerify(string $token, string $secret): ?array {
    $parts = explode('.', $token);
    if (count($parts) !== 3) return null;
    [$header64, $payload64, $sig64] = $parts;

    $expected = rtrim(strtr(base64_encode(hash_hmac('sha256', "$header64.$payload64", $secret, true)), '+/', '-_'), '=');
    if (!hash_equals($expected, $sig64)) return null;

    $padded  = $payload64 . str_repeat('=', (4 - strlen($payload64) % 4) % 4);
    $payload = json_decode(base64_decode(strtr($padded, '-_', '+/')), true);
    if (!is_array($payload)) return null;
    if (isset($payload['exp']) && $payload['exp'] < time()) return null;
    return $payload;
}

$claims = jwtVerify($_GET['token'] ?? '', getenv('JWT_SECRET'));
if (!$claims) { http_response_code(401); exit('invalid or expired token'); }
echo "Hello user #{$claims['sub']}";
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.