DEV Community

Cover image for Simple way to generate random string in PHP
Deepak Singh
Deepak Singh

Posted on

Simple way to generate random string in PHP

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));
Enter fullscreen mode Exit fullscreen mode

Simple way to generate random string in PHP
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;
}
Enter fullscreen mode Exit fullscreen mode

Execute:

$rd = getRadomSeed();
echo $rd;
Enter fullscreen mode Exit fullscreen mode

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! 🦃

Discussion (0)