PHP Reference ยท Math Functions
PHP random_bytes() function
Reference for PHP random_bytes(): generate cryptographically secure random byte strings, encode them with bin2hex() or base64, and use them for tokens.
random_bytes() returns a string of the requested length filled with cryptographically secure random bytes. The result is raw binary, not text: it can contain null bytes and values that are not valid UTF-8. To store or print it, encode it first with bin2hex(), base64_encode() or similar.
It is the right building block for session identifiers, CSRF tokens, password-reset links, API keys, salts and encryption keys or nonces. The bytes come from the operating system's secure random source and cannot be seeded or predicted.
<?php $token = bin2hex(random_bytes(16)); echo strlen($token); // 32
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
random_bytes(int $length): string
| Name | Description |
|---|---|
$length |
The number of random bytes to return. Must be at least 1. |
Return value: a binary string of exactly $length bytes.
Errors: a ValueError if $length is less than 1. A Random\RandomException if the system has no secure source of randomness.
Usage notes
- It returns bytes, not characters.
random_bytes(16)is 16 bytes long, butbin2hex()turns it into 32 characters andbase64_encode()into 24. - How many bytes? 16 bytes (128 bits) is plenty for unguessable identifiers. 32 bytes suits long-lived secrets and keys.
- Don't echo or log raw output: it is not valid text and may corrupt a page, a log file or JSON. Encode it.
- Unbiased ranges need
random_int(). Takingord($byte) % 10favors the lower digits. - Comparing secrets: use
hash_equals()to avoid timing leaks, and store a hash of long-lived tokens. - Alternatives:
uniqid(),md5(time())andmt_rand()are guessable and must not be used for secrets. - PHP 8.3+:
Random\Randomizer::getBytes()offers the same with a pluggable engine; withnew Random\Engine\Secure, it is equally strong.