How to Generate Cryptographically Secure Random Boolean Value in PHP?

Find out cryptographically strong ways of generating a random boolean value in PHP

For critical systems, for example where unbiased results are essential, you can generate a cryptographically secure random boolean value using either of the following:

Please note that using either of the above functions would require some amount of processing time to generate a cryptographically secure random value. Therefore, for simpler cases, you should consider using a less CPU-intensive approach instead.

Using random_int()

You can use the random_int() function to generate a cryptographically secure pseudo-random integer, which can then be cast to a boolean like so:

// PHP 7+
$randNum = random_int(0, 1);
$randBool = (bool) $randNum;

Using ord() and openssl_random_pseudo_bytes()

To generate a cryptographically strong random result you could use ord() and openssl_random_pseudo_bytes() functions together like so:

// PHP 5+
$pseudoRandStr = openssl_random_pseudo_bytes(1, true);
$randNum = ord($pseudoRandStr);
$randBool = $randNum >= 128;

This works in the following way:

  1. Generate a cryptographically strong pseudo-random string of bytes of length one using openssl_random_pseudo_bytes();
  2. Use the ord() function to convert the pseudo-random string from the previous step to a value between 0 and 255;
  3. Compare that value to the median 128 to get a random boolean value.

Passing true as the second argument to openssl_random_pseudo_bytes() uses a "cryptographically strong" algorithm to generate the result.

Wherever possible, use random_int() instead, or a polyfill for it.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.