PHP Functions For Generating Random Strings and Bytes
Generates a random string of letters and numbers. This function uses the PHP rand(), a string concatenation and simple string repetition to generate a random alphanumeric string. It uses the list of alphanumeric characters and numbers as base set and shuffles and repeats them to get a string with the desired length.
Using a secure random number generator is a key component for generating secure data. For this reason it is very important to choose the right function for your application.
Most developers are familiar with the PHP rand() and mt_rand() functions but these are not suitable for generating passwords, salt for hashing or cryptography. PHP 7.0 has a new random_int() function that provides a CSPRNG (Cryptographically Secure Pseudo Random Number Generator) and it is recommended to use this for all random number and byte generation needs. The random_int() function throws an Exception if it could not yield a senescence of numbers with sufficient randomness and does not fallback to any insecure RNG source like the userland RNG on Windows. The random_int() function is also seeded from a cryptographically strong source such as the Mersenne Twister RNG.
The stdrandom() function from the stdlib extension is a good choice for generating random byte strings and it is available on all platforms. For a cross-platform solution you can also try the random_bytes() function from the openSSL extension. Alternatively, the Anthony Ferrara's RandomLib is another option for random number and string generation.