Random String

Looking for a simple function that would produce random and reliably unique characters, i came across many simple code snippets that didn’t do the job as well as I needed.

The best function i found was over at phptoys.com I’ve modified it slightly to make it shorter.

e.g

echo generatePassword();
function generatePassword($length=7,$level=4){
   list($usec, $sec) = explode(' ', microtime());
   srand((float) $sec + ((float) $usec * 100000));
   $str1 = "0123456789"; $str2 = "abcdfghjkmnpqrstvwxyz";
   $str3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; $str4 = "_-=";
   $validchars[1] = $str1;
   $validchars[2] = $str1.$str2;
   $validchars[3] = $str1.$str2.$str3;
   $validchars[4] = $str1.$str2.$str3.$str4;
   $password  = "";$counter   = 0;
while ($counter < $length) {
 $actChar = substr($validchars[$level],
rand(0, strlen($validchars[$level])-1), 1);
     // All character must be different
     if (!strstr($password, $actChar)) {
        $password .= $actChar;
        $counter++;
     }
   }
return $password;}

Leave a Reply