Skip to content

Core\Random::token

Core\Random::token(uint $bytes = 32): stringCore\Random::token(
    uint $bytes = 32,
): string

Makes a random text for a session ID, a password reset link or an API key.

Core\Random::token draws random bytes from a cryptographic random generator and writes them as hex. Nobody can guess the next token from the tokens before it. By default it draws 32 bytes, and the result is a string of 64 characters. You can ask for another number of bytes. The string is always twice as long as that number, and it contains only the characters 0 to 9 and a to f.

Asking for zero bytes throws an error. An empty token is equal to every other empty token, so it protects nothing.

Good to know: when you need the raw bytes for a key, use Core\Random::bytes.

Parameters

  • $bytesuintdefault 32How many random bytes to use, 32 by default. The string has twice as many characters.

Return value

Returns string. A string of 2 * $bytes hex digits, 0–9 and a–f.

Errors

  • RuntimeError$bytes is 0, because an empty token is equal to every other empty token. It is also thrown when the result is larger than a buffer this process can allocate.

Examples

A session id

<?nvs
// Shows how to make a random session ID, and how long it is.
// Without an argument, `Core\Random::token` draws 32 bytes. This prints 64.
string $session = Core\Random::token();
echo Core\Str::length($session), "\n";
// With 8 bytes, the token has 16 characters. This prints 16.
echo Core\Str::length(Core\Random::token(8)), "\n";
// The token is hex, so `Core\Encoding::fromHex` turns it back into the 32 bytes. This prints 32.
echo Core\Bytes::length(Core\Encoding::fromHex($session)), "\n";
Output
64
16
32

Zero bytes is an error

<?nvs
// Shows what happens when a program asks for a token of zero bytes.
// The size here comes from a setting that was left empty.
uint $size = 0;
// `Core\Random::token(0)` throws an error. An empty token would protect nothing.
try {
string $token = Core\Random::token($size);
echo $token, "\n";
} catch (Throwable $e) {
echo 'Error: ', $e->message, "\n";
}
Output
Error: Core\Random::token(): a token of zero bytes is the empty string, which is not a token — draw at least one byte

A password reset link

<?nvs
// Shows how to make the link in a password reset email.
// The token goes into the link. The program also stores it, to compare it later.
string $token = Core\Random::token();
string $link = 'https://example.com/reset?token=' . $token;
// The token is different on every run, so this prints only the length of the link: 96.
echo Core\Str::length($link), "\n";
// Hex is safe in a URL, so the link needs no extra encoding. This prints `same`.
echo Core\Uri::encodeComponent($token) == $token ? 'same' : 'changed', "\n";
Output
96
same