How Can I Generate a Random Alphanumeric String in PHP?
The need to generate a unique random alphanumeric string of a given length is very common. You may need it for various purpose like creating a random username or a filename. In this article, you will learn about different methods that can be used to generate random alphanumeric string in PHP.
Using str_shuffle() to Generate a Random String
In this section, we will be using different string functions to create our own random alphanumeric string generator function. Here is the first version of our function that generates a random alphanumeric string.
PHP
function random_alphanumeric_string($length) {
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
return substr(str_shuffle($chars), 0, $length);
}
// Output — FtUqw9QpC1
echo random_alphanumeric_string(10);
// Output — ZIPNz1kKvJ
echo random_alphanumeric_string(10);
We begin by creating a $chars
variable that stores all the characters we will be using to create our random string generator. You could also add other characters like #, $, &, @
to the mix. After that, we have used the str_shuffle() function in PHP to randomly shuffle the alphanumeric string value stored in $chars
. Finally, we return the first $length
characters of the shuffled string using the substr() function in PHP.
For simple cases, this solution should be sufficient. However, there are two issues with it in its current form. First, the maximum length of string can only be 62 (10[0-9] + 26[a-z] + 26[A-Z] = 62) characters. Second, the characters inside the generated string will never repeat. We can solve both these issues with the help of str_repeat() function in PHP which repeats a string given number of times. Here is the second iteration of our function:
PHP
function random_alphanumeric_string($length) {
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
return substr(str_shuffle(str_repeat($chars, ceil($length/strlen($chars)) )), 0, $length);
}
// Output — Z4VIz4gvnb0NQ6KHUej1lpCiYVbFdArA2Hw9RdkPyeftFGnaiwDEsPm7JjuLWSxMBDhZ72KT56xIkhqQtrmgGozaM0uf9cX83U15
echo random_alphanumeric_string(100);
We divide the length of required random string with the length of the seed string, take its ceiling value and then repeat the seed string calculated number of times. For example, length of $chars
is 62. If the supplied $length
value is 100, ceil(100/62)
becomes 2. This means that our seed string will be repeated twice making its total length 124. The substr()
function can then take the first 100 characters after the string has been shuffled.
Now, the characters inside our random string will start repeating once its length becomes more than 62. However, this means that any random alphanumeric character sequence generated by our function with less than or equal to 62 characters will still have unique characters. We can slightly modify our function and specify the number of times the characters may be repeated along with the length of generated string.
PHP
function random_alphanumeric_string($length, $repeats) {
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
return substr(str_shuffle(str_repeat($chars, $repeats)), 0, $length);
}
// Output — AJ9H8NBKK4
echo random_alphanumeric_string(10, 3);
// Output — Wd8YtZcwqT
echo random_alphanumeric_string(10, 3);
Now, the characters will repeat even if the string length is less than 62. This makes the generated string less predictable. However, you still should not use it cryptographic purposes like generating passwords. This is because str_shuffle()
uses rand()
to shuffle the string and rand()
is the secure cryptography wise.
Using md5() and sha1() to Generate a Random String
The md5() function available in PHP can be used to calculate the md5 hash of a given string. For our purposes, we can supply it a random integer using mt_rand()
or the current timestamp value using time()
. The hash of the given input is returned as a 32 character hexadecimal number. This means that the maximum length of the returned hash will be 32 characters. We can use the substr() function to extract a part of the output as our random string. Here is an example:
PHP
function random_md5_string($length) {
return substr(md5(time()), 0, $length);
}
// Output — e4c0c18a8dba
echo random_md5_string(12);
// Output — b2ac061a4b0aab170474f28a
echo random_md5_string(24);
Similarly, you can also use the sha1()
function to calculate the sha1 hash of a given string. Just like the previous example, we can supply it with an input value using time()
or mt_rand()
. The maximum length of returned hexadecimal string in this case would be 40 characters.
PHP
function random_sha1_string($length) {
return substr(sha1(mt_rand()), 0, $length);
}
// Output — 52550a827ba2458e7128e2f5a7ccd34d3a7b
echo random_sha1_string(36);
Using the random_bytes() Function
The methods we have used so far for generating our string are not meant to be used in cryptography based work. In such cases, you can use the random_bytes() function in PHP to generate cryptographically secure random bytes. This function is relatively new and only available in PHP 7. Here is an example of a random string generated using the bin2hex()
and random_bytes()
functions.
PHP
function random_string($length) {
echo substr(bin2hex(random_bytes($length)), 0, $length);
}
// Output — c92b5d7247241d7a8a63
echo random_string(20);
The random_bytes()
function returns $length
number of pseudo-random bytes. We are using the bin2hex() function in PHP to convert the returned binary string into a hexadecimal value. Finally, we extract the first $length
characters from the hexadecimal string using substr()
function.
One major advantage of using random_bytes()
is that it is cryptographically secure. However, it is only available in PHP 7.
Quick Summary
Let’s recap everything that we have covered in this tutorial.
- You can use
str_shuffle()
to shuffle all the characters in an alphanumeric string. This alphanumeric string will consist of all the characters that you want to appear in your random string. After shuffling it, all the characters will be in random order and you can pick a substring of given length out of the shuffled string to get your random alphanumeric string. - If you only need a random hexadecimal string, you can use the
md5()
function to get a 32 characters long string. Similarly, you can use thesha1()
function to get random hexadecimal strings with 40 characters. - If you want to generate cryptographically secure random strings, you should consider using the
random_bytes()
function in PHP. You can then use thehex2bin()
function to convert those random bytes into hexadecimal strings. However, therandom_bytes()
function is only available in PHP 7.
Let me know if there is anything that you would like me to clarify in this tutorial. Also, you are more than welcome to comment if you know other techniques to generate a random alphanumeric string in PHP.
Rate this post —