note 26931 deleted from function.mt-rand by bjori
| From: | bjori@php.net | Date: | Sun, 16 Apr 2006 12:16:44 +0000 |
| Subject: | note 26931 deleted from function.mt-rand by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-108250@lists.php.net to get a copy of this message | ||
Note Submitter: michael at something hotmail dot com
----
An answer to demogracia:
Your first function "simpleRandString" is perfect, but the second function
"randString" has a flaw: since you use the random generator to go into one of the three
cases, every case will be used 1/3 of the time. Since case 1 has less possibilites than the others
(10 vs. 26 and 26), the output can be more easily guessed: numbers will appear more often than
average.
Here is the same function without this flaw:
function randString($length=16)
{
$newstring="";
if($length>0)
{
while(strlen($newstring)<$length)
{
$randnum = mt_rand(0,61);
if ($randnum < 10)
{$newstring.=chr($randnum+48);}
elseif ($randnum < 36)
{$newstring.=chr($randnum+55);}
else
{$newstring.=chr($randnum+61);}
}
}
return $newstring;
}
You can make it a bit faster by not relying on "strlen" for every pass:
function randString($length=16)
{
$newstring="";
if($length>0)
{
while(strlen($newstring)<$length)
{
$randnum = mt_rand(0,61);
if ($randnum < 10)
{$newstring.=chr($randnum+48);}
elseif ($randnum < 36)
{$newstring.=chr($randnum+55);}
else
{$newstring.=chr($randnum+61);}
}
}
return $newstring;
}