PHP

Build & Sign a JWT (HS256)

admin by @admin ADMIN
2m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Generate a JWT manually using only base64-url and hash_hmac — no library required. Demonstrates header/payload/signature concatenation and the exp claim.
PHP
Raw
<?php
function jwtSign(array $claims, string $secret, int $ttlSec = 3600): string {
    $b64 = fn(string $s) => rtrim(strtr(base64_encode($s), '+/', '-_'), '=');

    $now = time();
    $claims = array_merge(['iat' => $now, 'exp' => $now + $ttlSec], $claims);

    $header  = $b64(json_encode(['alg' => 'HS256', 'typ' => 'JWT']));
    $payload = $b64(json_encode($claims, JSON_UNESCAPED_SLASHES));
    $signing = "$header.$payload";
    $sig     = $b64(hash_hmac('sha256', $signing, $secret, true));
    return "$signing.$sig";
}

$token = jwtSign(['sub' => 42, 'role' => 'admin'], getenv('JWT_SECRET'));
echo $token;
Tags

Save your own code snippets

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