How to generate a random String in PHP
John Mwaniki / Updated on 07 Jul 2024Generating random strings is a common task for developers in various scenarios when making applications.
A random string is a sequence of characters that are created randomly and has no predictable pattern.
This string can be used for various purposes like generating a password, creating a unique identifier, or generating a random username.
In this article, we will cover different methods of generating a random string in PHP and their use cases.
Use Cases of Generating a Random String
- Password Generation: In applications where a user needs to create a new or reset their existing account password, generating a random string is necessary to provide a strong and secure password that is not easy to guess.
- Unique Identifier: In scenarios where a unique identifier is needed, like generating a session ID, tracking users, or creating unique filenames, a random string is a good choice.
- Captcha: In web applications where security is a concern, generating a random string for a captcha can be useful to prevent automated attacks.
- In Cryptography: Random strings are used as keys in cryptography to encrypt and decrypt sensitive information, and to generate other cryptographic elements such as digital signatures.
Generating a Random String in PHP
There are quite a number of ways in which you can generate a random string in PHP. Below we explore several of them:
- Using Brute Force
- Using the uniqid() Function
- Hashing a Randomly Generated Number
- Using the random_bytes() function
- Using the openssl_random_pseudo_bytes() function
Using Brute Force
This is the easiest to understand among them.
First, we create a string comprising all the possible characters that we would want to include in the resulting random string. To include numbers (0-9), lowercase letters (a-z), and uppercase letters (A-Z), we create the string as below:
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
Then we create the variable that will hold the random string and assign it a value of an empty string.
$randomString = '';
Next, we randomly pick characters (each at a time) from the string we created above and concatenate them to the random string until its desired length is reached.
To achieve this, we generate a random number which will be used as an index to get the character from the string at that index. This number should fall anywhere from 0 to the string length-1. The purpose of subtracting 1 is because the indices start from 0. The index for the first character is 0 and therefore the index for the last character is equal to the length of the string minus 1.
To generate this random number, we can use various functions such as rand()
, mt_rand()
, or random_int()
. In this case here, we will use the mt_rand()
function.
$index = mt_rand(0, strlen($characters) - 1);
Below is how you get the character at the randomly generated index on the string and concatenate it to the random string.
$randomString .= $characters[mt_rand(0, strlen($characters) - 1)];
To get a random string of your desired length we need to run the above code within a loop where $length
is your preferred length eg 10, 20, 25, etc.
$length = 10;
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[mt_rand(0, strlen($characters) - 1)];
}
Finally, we will put the above code within a function where you will be passing the length as the argument when calling it and the function will be returning the random string of that length as the output.
<?php
function generateRandomString($length) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[mt_rand(0, strlen($characters) - 1)];
}
return $randomString;
}
/**
Calling the function with a length of 20 and printing the output
**/
echo generateRandomString(20);
?>
Output:
gBfaw4YwbnTZGBLU9yZ8
Using the uniqid() Function
The uniqid()
function is an in-built PHP function that generates a unique ID based on the current time in microseconds. It returns the unique identifier, as a string which is by default 13 characters long.
Example
<?php
$randomstring = uniqid();
echo $randomstring;
?>
Output:
64401d70e81ef
Hashing a Randomly Generated Number
Using this method, we first generate a random number using a function such as rand()
, mt_rand()
, or random_int()
.
Then we hash the generated number using a hashing function such as md5()
, sha1()
, and hash()
which returns an Alpha-Numeric hashed string.
Example 1
<?php
$random_num = rand();
$randomString = hash("sha256", $random_num);
echo $randomString;
?>
Output:
24fe96f9e1ea0f4368ea838ec837f7c4627e89e666dc712f46dee40dfb1a879b
Example 2
<?php
$num = random_int(1, 20);
$str = md5($num);
echo $str;
?>
Output:
98f13708210194c475687be6106a3b84
Example 2
<?php
$number = mt_rand(11, 99);
$str = sha1($number);
echo $str;
?>
Output:
2d0c8af807ef45ac17cafb2973d866ba8f38caa9
As you may have noticed, different hashing algorithms generate strings of different lengths but for all the strings generated using the same algorithm, the length will always be constant.
To have a custom length for the strings generated using these methods, simply truncate the string to shorten it or concatenate it with another to lengthen it.
If the string is to be used as a cryptographic key, its randomness and unpredictability are crucial in ensuring the security and confidentiality of the information being transmitted or stored. It's therefore advised to use any of the below methods instead when generating cryptographically secure strings.
Using the random_bytes() function
The random_bytes()
function is an in-built PHP function that generates a string of cryptographic random bytes that are suitable for cryptographic use.
This function accepts length (must be 1 or greater) as the argument and returns a string containing the requested number of cryptographically secure random bytes.
We then convert these bytes into a hexadecimal format using the bin2hex()
function.
Example
<?php
$rand_bytes = random_bytes(20);
$randomString = bin2hex($rand_bytes);
echo $randomString;
?>
Output:
e96a830fe99559d50b6bf92a833d1ea81a8f201f
Using the openssl_random_pseudo_bytes() function
The openssl_random_pseudo_bytes()
function is an in-built function in PHP that generates a pseudo-random string of bytes that are cryptographically secure.
This function accepts length as the argument and returns the generated string of bytes.
We can the use bin2hex()
function to convert these bytes to a hexadecimal format string.
Example
<?php
$randomString = bin2hex(openssl_random_pseudo_bytes(25));
echo $randomString;
?>
Output:
0dbeb4633f36da02c9262f018a9b7bc17569431f63daa71221
Now you can comfortably generate random strings in PHP using any of the methods covered in this article.