Codectionary / Developer documentation / PHP

PHP secure random tokens

random_bytes obtains cryptographically secure random bytes. Encoding with bin2hex makes those bytes printable for tokens without pretending random output has a fixed value.

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;
  1. 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

Specifications & further reading