• Home
  • blog
  • Randomness in PHP – Do You Feel Lucky?

Randomness in PHP – Do You Feel Lucky?

Cryptography Randomness in PHP

This article analyzes problems related to random number generation used for cryptography purposes. PHP 5 does not provide an easy mechanism for generating cryptographically strong random numbers, while PHP 7 solves this by introducing a couple of CSPRNG functions.

What is a CSPRNG?

Quoting Wikipedia, a Cryptographically Secure Pseudorandom Number Generator (CSPRNG) is a pseudo-random number generator (PRNG) with properties that make it suitable for use in cryptography.

A CSPRNG could be mainly useful for:

  • Key generation (e.g. generation of complicated keys)
  • Creating random passwords for new user accounts
  • Encryption systems

A central aspect to keeping a high security level is the high quality of randomness.


PHP 7 introduces two new functions that can be used for CSPRNG: random_bytes and random_int.

The random_bytes function returns a string and accepts as input an int representing the length in bytes to be returned.

Continue reading %Randomness in PHP – Do You Feel Lucky?%