This content originally appeared on DEV Community and was authored by Deepak Singh
While developing an application, sometimes it requires generating a random but unique string, e.g. Password Generator, CSRF token, and many more.
There are so many methods to generate random and unique strings in PHP. For Example:
rand();
uniqid();
bin2hex(random_bytes(20));
But I prefer my way to generate a random string by using existing PHP functions and bit improvisation.
Here is the function:
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! 🦃
This content originally appeared on DEV Community and was authored by Deepak Singh

Deepak Singh | Sciencx (2021-11-26T06:18:40+00:00) Simple way to generate random string in PHP. Retrieved from https://www.scien.cx/2021/11/26/simple-way-to-generate-random-string-in-php/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.