The PHP Function Random_Bytes
The php function random_bytes is used to generate a string of pseudo random bytes. The length of the generated string of bytes is determined by a parameter value passed to the function. The php function also indicates if the generated string of bytes was produced with a cryptographically strong algorithm, this is done via an optional 'crypto_strong' parameter.
The random_bytes function is recommended over the older rand() random number generator because it will fail to return a string of bytes in some cases due to a lack of sufficient entropy. The 'crypto_strong' parameter will help avoid these problems.
A cryptographically secure pseudo random number generator is a required part of any application that uses random values, such as passwords or keys. The random_bytes function in PHP provides a way to ensure that you have a strong random number generator when creating a string of characters for a password or key.
Before PHP 7.1, rand() (which is still used by the vast majority of web applications) relied on a simple algorithm called Mersenne Twister to produce its random numbers. This random number generator is not considered to be cryptographically secure as it can be re-sequenced with an identical seed value.
PHP 7.2 introduced the openssl_random_pseudo_bytes function that uses Xoshiro256StarStar as a CSPRNG and is more likely to be cryptographically strong than Mersenne Twister. For this reason, using the CSPRNG random_bytes is the best choice for any application that requires a cryptographically secure random number generator.