random_bytes()

random_bytes() — Get cryptographically secure random bytes.

Built-in function of PHP 8.5. The manual lists it as available in PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

Generates a string containing uniformly selected random bytes with the requested length.

Signature

random_bytes(int $length): string

Parameters

ParameterTypeWhat it takes
$lengthintThe length of the random string that should be returned in bytes; must be 1 or greater.

Return value

A string containing the requested number of cryptographically secure random bytes.

Example

A runnable snippet:

$bytes = random_bytes(5); var_dump(bin2hex($bytes));

Output:

string(10) "385e33f741"

Changelog

VersionChange
8.2.0In case of a CSPRNG failure, this function will now throw a Random\RandomException. Previously a plain Exception was thrown.

See also

random_int(), bin2hex(), base64_encode()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page random_bytes() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.