Syntax
$token = bin2hex(random_bytes(32));Examples
PHP secure random tokens
Run as a PHP 8.0+ CLI script, for example php example.php. The multibyte example additionally requires mbstring.
<?php
$token = bin2hex(random_bytes(32));
echo strlen($token), PHP_EOL;
echo ctype_xdigit($token) ? 'hexadecimal' : 'unexpected', PHP_EOL;- Output: 64, then hexadecimal. The generated token differs between runs; 32 bytes become 64 hexadecimal characters.
Best practices
- Do not substitute mt_rand for security tokens. Handle failures and define token storage, expiry and verification separately.
Runtime & versions
PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
PHP Manual