This article demonstrates how to generate a random string in PHP.

1. Using random_bytes() function

In PHP 7, you can use the random_bytes() function to generate cryptographically secure random bytes of the specified length. The returned bytes can be converted into a string containing the hexadecimal representation.

Download  Run Code

 
The CSPRNG functions random_bytes() and random_int() were added to PHP in version 7.0. These functions can be used for cryptographic purposes, such as to generate random initialization vectors and salt values. If you’re still on PHP 5.x, here’s the PHP 5 polyfill for these functions.

2. Using openssl_random_pseudo_bytes() function

Prior to PHP 7.0, you may also use the openssl_random_pseudo_bytes() function to generate a pseudo-random string of bytes having the specified length. It uses a cryptographically strong algorithm to produce the pseudo-random bytes. As of PHP 7.4.0, this function throws an exception on failure.

Download  Run Code

3. Using random_int() function

If you want to limit the allowed characters in the random string, you can write a custom routine for generating random strings. The most common and effective approach is to randomly choose characters from the desired range using the random_int() function, and append that character to a string until the desired length is reached.

Here’s an example of how you might achieve that. It generates a random ASCII alphanumeric string using a range consisting of upper- and lower-case alphabets and digits. As already mentioned earlier, the random_int() function was introduced in PHP 7 and uses a cryptographically secure pseudorandom number generator (CSPRNG).

Download  Run Code

4. Using str_shuffle() function

If you don’t really need the random string to be cryptographically safe, you can simply shuffle the desired set of characters using the str_shuffle() function. Then, you can extract a substring from the first $n characters of the shuffled string, where $n is the desired length.

Download  Run Code

 
Alternatively, you can get the MD5/SHA-512 hash of the current Unix timestamp and extract the portion of the hash string of desired length. You can get the current Unix timestamp in microseconds with microtime() function. Note that, as of PHP 7.1.0, str_shuffle() internally uses the Mersenne Twister Random Number Generator, which is not suitable for cryptography purposes.

Download  Run Code

That’s all about generating a random string in PHP.