PHP Function Reference

PHP random_bytes() Function



The PHP random_bytes() function generates cryptographically secure pseudo-random bytes. This is suitable for cryptographic use, such as when generating salts, keys or initialization vectors.

The sources of randomness used for this function are as follows:

  • On Windows, CryptGenRandom() will always be used. As of PHP 7.2.0, the CNG-API will always be used instead.
  • On Linux, the getrandom(2) syscall will be used if available.
  • On other platforms, /dev/urandom will be used.
  • If none of the aforementioned sources are available, then an Exception will be thrown.

Syntax

random_bytes(length)

Parameters

length Required. Specify the length of the random string that should be returned in bytes.

Return Value

Returns a string containing the requested number of cryptographically secure random bytes.

Exceptions

  • If an appropriate source of randomness cannot be found, an Exception will be thrown.
  • If invalid parameters are given, a TypeError will be thrown.
  • If an invalid length of bytes is given, an Error will be thrown.

Example: random_bytes() example

The example below shows the usage of random_bytes() function.

<?php
//generating cryptographically 
//secure pseudo-random bytes 
//of specified bytes
$byte1 = random_bytes(5);
var_dump(bin2hex($byte1));

$byte2 = random_bytes(6);
var_dump(bin2hex($byte2));

$byte3 = random_bytes(7);
var_dump(bin2hex($byte3));
?>

The output of the above code will be similar to:

string(10) "05867f17d7"
string(12) "3be97103c587"
string(14) "06bb66526d2a1a"

❮ PHP CSPRNG Reference