While developing an application, sometimes requires generating random strings in PHP, e.g. Password Generator, CSRF token, encryption, and many more.
This section discusses how to generate random strings in PHP.
The first function we will discuss is the mt_rand() function. This function generates a random number between 0 and mt_getrandmax(). It takes no parameters and returns a string of length 10 characters.
The second function is rand(). This function generates a random number between 0 and 1. It takes no parameters and returns a string of length 6 characters.
The PHP language has a number of functions that generate random strings. These functions can be used to encrypt sensitive data and can also be used as keys in encryption algorithms.
The following are the three most commonly used PHP random string functions:
1) The rand() function generates a sequence of pseudo-random numbers between 0 and 1. This function is not cryptographically secure, but it does provide a good source of pseudorandom numbers for many applications.
2) The mt_rand() function uses a Mersenne Twister algorithm to generate long sequences of pseudorandom numbers.
3) The uniqid() function generates an identifier that is unique across the server on which it is running, but not necessarily globally unique. This function should not be used for cryptographic purposes as it relies on the uniqueness of the machine’s ID to make identifiers unguessable
There are so many methods to generate random strings and unique strings in PHP.
For Example in:
rand();
uniqid();
bin2hex(random_bytes(20));
Generate random strings in PHP
But I prefer my way to generate a random string by using existing PHP functions and bit improvisation. You can try another method or this method.
Here are the PHP functions:
function random_seed(){
list($usec, $sec) = explode(' ', microtime());
return $sec + $usec * 1000000;
}
function getRadomSeed(){
mt_srand(random_seed());
$prefix = substr(str_shuffle(str_repeat($x='abcNOPQRSTUVWXYZdefghijklmnopqrstuvwxyzABCDEFGHIJKLM', ceil(5/strlen($x)) )),1,5);
$suffix = substr(str_shuffle(str_repeat($x='wxyzABCDEFGHIJKLMNOabcdefghijklmnopqrstuvPQRSTUVWXYZ', ceil(5/strlen($x)) )),1,5);
$randval = mt_rand();
if(strlen($randval) % 2 == 0){
$random = $prefix.$randval.$suffix;
}else if(strlen($randval) % 3 == 0){
$random = $prefix.$suffix.$randval;
}
else{
$random = $randval.$prefix.$suffix;
}
return $random;
}
Execute:
$rd = getRadomSeed();
echo $rd;
Just to be sure that this is not the only way to generate random strings in PHP. I am just sharing one of my ways to generate random strings.
Happy Thanksgiving! 🦃