This topic is locked

Generate Random Alpha + Numbers

9/7/2011 2:09:06 PM
PHPRunner Tips and Tricks
F
FunkDaddy author

I needed to generate a 64 digit alpha-numeric string to be used as a unique value to be stored in a users type table which controls specific security features.
I found this post http://www.lost-in-code.com/programming/php-code/php-random-string-with-numbers-and-letters/
I tweaked the code above as follows to ensure that it always provides an exact length as declared in the $length variable:



function genRandomString() {

$length = 64;

$characters = "0123456789abcdefghijklmnopqrstuvwxyz";

$characters_length = strlen($characters)-1;

for ($p = 1; $p <= $length; $p++) {

$string .= $characters[mt_rand(0, $characters_length)];



}

echo "The Result is: ".$string; //for testing only so you can see the results

echo "
Length :".strlen($string); //for testing only so you can see the results



return $string;



}

genRandomString(); //for testing only so you can see the results


This line in the above code "$characters_length = strlen($characters)-1; " gives us the true length and we use it as the max random value/ Otherwise, without the minus 1 we may accidentally get a random value that exceeds the actual $characters array and this populate a blank value, resulting in string that is actually shorter than specified in the $length variable.
Cheers,