Generate a random string in PHP
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php function random_str($length = 32) { return bin2hex(random_bytes($length / 2)); } $length = 20; $rand_str = random_str($length); echo $rand_str; /* Sample Output: f16508be131493343b03 */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php function random_str($length = 32) { return bin2hex(openssl_random_pseudo_bytes($length / 2)); } $length = 20; $rand_str = random_str($length); echo $rand_str; /* Sample Output: 909c06d2342b4c9b3b0b */ ?> |
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).
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php function random_str( $length = 20, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ) { $rand_str = ''; $max = mb_strlen($chars) - 1; for ($i = 0; $i < $length; $i++) { $rand_index = random_int(0, $max); $rand_str .= $chars[$rand_index]; } return $rand_str; } $length = 20; $rand_str = random_str($length); echo $rand_str; /* Sample Output: LJStw6pLYJgNtpLRUFhJ */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php function random_str( $length = 20, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ) { return substr(str_shuffle($chars), 0, $length); } $length = 20; $rand_str = random_str($length); echo $rand_str; /* Sample Output: g9n3YMxlCyzbcXwOvfuU */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php function random_str($length = 32) { return substr(str_shuffle(MD5(microtime())), 0, $length); } $length = 10; $rand_str = random_str($length); echo $rand_str; ?> |
That’s all about generating a random string in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)