Skip to main content

How to Create a JWT in PHP with firebase/php-jwt

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

The firebase/php-jwt package creates JSON Web Tokens in PHP with one static call: JWT::encode($payload, $key, 'HS256') turns an array of claims into a signed token string.

Syntax​

Syntax
$token = JWT::encode(<payload>, <key>, '<algorithm>', <key id>);
PartWhat it does
<payload>The claims, as an array, such as ['sub' => 'ada', 'exp' => ...].
<key>The signing key. For HS256, the shared secret as a string of bytes.
'<algorithm>'The algorithm, such as 'HS256'. Required.
<key id>Optional. Written to the header as kid, the ID of the key that signed the token.

The doc comment on JWT::encode in the php-jwt source: "Converts and signs a PHP array into a JWT string." Its signature is encode(array $payload, $key, string $alg, ?string $keyId = null, ?array $head = null): string.

The Example​

The example creates a token for the user ada with the role reader, issued now and valid for 10 minutes, signs it with HS256 and prints it.

The key is 32 random bytes, made with openssl rand -base64 32 and written as base64. It sits in the code only so the example runs as it is. A real application loads its key from configuration, such as an environment variable or a secret store, and never keeps it in the source.

Prerequisites​

  • PHP and Composer. This guide uses PHP 8.6.0 and Composer 2.11.3.

Step 1: Create the Project​

Terminal
mkdir demo
cd demo
composer require firebase/php-jwt

composer require creates composer.json, downloads the package into vendor/ and writes the autoloader:

Output
./composer.json has been created
Running composer update firebase/php-jwt
Loading composer repositories with package information
Updating dependencies
Lock file operations: 1 install, 0 updates, 0 removals
- Locking firebase/php-jwt (v7.2.2)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
- Downloading firebase/php-jwt (v7.2.2)
- Installing firebase/php-jwt (v7.2.2): Extracting archive
2 package suggestions were added by new dependencies, use `composer suggest` to see details.
Generating autoload files
No security vulnerability advisories found.
Using version ^7.2 for firebase/php-jwt

Step 2: Write the Code​

Create main.php:

main.php, which loads Composer's autoloader, uses Firebase\JWT\JWT, decodes the base64 key, builds a payload with sub ada, role reader, iat now and exp 600 seconds later, signs it with JWT::encode and HS256, and echoes the token.

main.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Firebase\JWT\JWT;

// The signing key: 32 random bytes, written as base64.
// It's in the code only for this example; a real app loads it from its configuration.
$key = base64_decode('VfosHbT9z3nikPe56UUfKL9Y6mF2oOui09j4GCY0AYs=', true);

$now = time();
$payload = ['sub' => 'ada', 'role' => 'reader', 'iat' => $now, 'exp' => $now + 600];

$token = JWT::encode($payload, $key, 'HS256');
echo "{$token}\n";

require loads Composer's autoloader, so JWT is found when used. base64_decode(…, true) turns the base64 text into the 32 key bytes. time() is the current Unix time, and + 600 is ten minutes later.

Step 3: Run It​

Terminal
php main.php
Output
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZGEiLCJyb2xlIjoicmVhZGVyIiwiaWF0IjoxNzk1NjgyNTI0LCJleHAiOjE3OTU2ODMxMjR9.Sp8wInV9IALIsVZVYs-iUh07E9AMeM-QQxyOt2unkeo

A zsh terminal where php main.php prints a JWT made of three base64url parts separated by dots.

Your token will differ, because iat and exp hold the time you run it. Decoded from base64url, the header and payload read:

Header
{"typ":"JWT","alg":"HS256"}
Payload
{"sub":"ada","role":"reader","iat":1795682524,"exp":1795683124}

php-jwt wrote typ before alg in the header, and kept the payload in the array's order.

Add a Key ID​

The fourth argument becomes kid in the header. JWT::encode(['sub' => 'ada'], $key, 'HS256', 'key-2026-11') gave:

Header
{"typ":"JWT","alg":"HS256","kid":"key-2026-11"}

Common Mistakes​

MistakeWhat happensDo this instead
A short key, such as 'short'DomainException: Provided key is too shortUse 32 random bytes or more for HS256
A misspelled algorithm, 'HS257'DomainException: Algorithm not supportedUse a supported name, such as 'HS256'
Forgetting require __DIR__ . '/vendor/autoload.php'PHP can't find the JWT classLoad the autoloader first

Troubleshooting​

SymptomLikely causeFix
Provided key is too shortThe HMAC key has fewer bits than the hash, 256 for HS256Generate a 32-byte key
Algorithm not supportedThe algorithm name is wrongCheck the spelling
PHP Fatal error: Uncaught Error: Class "Firebase\JWT\JWT" not foundThe autoloader isn't loaded, or the package isn't installedRequire vendor/autoload.php; run composer require firebase/php-jwt

FAQ​

How long must the key be?​

php-jwt 7 checks it: for HMAC, the key must have at least as many bits as the hash, so 256 bits, 32 bytes, for HS256. That matches RFC 7518, section 3.2: "A key of the same size as the hash output (for instance, 256 bits for "HS256") or larger MUST be used with this algorithm."

Can I set other header fields?​

Yes, through the fifth argument, $head, an array of extra header values. JWT::encode(['sub' => 'ada'], $key, 'HS256', null, ['x-app' => 'demo']) gave the header {"typ":"JWT","x-app":"demo","alg":"HS256"}.

Conclusion​

JWT::encode($payload, $key, 'HS256') turns an array of claims into a signed JWT string. Pass a key of at least 32 random bytes, which php-jwt 7 enforces, and a key ID as the fourth argument when you rotate keys.

Additional Resources​