note 26931 added to function.mt-rand
| From: | michael at rack1 dot php dot net | Date: | Mon, 18 Nov 2002 09:49:37 +0000 |
| Subject: | note 26931 added to function.mt-rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-39626@lists.php.net to get a copy of this message | ||
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;
}
--
http://www.php.net/manual/en/function.mt-rand.php
http://master.php.net/manage/user-notes.php?action=edit+26931
http://master.php.net/manage/user-notes.php?action=delete+26931
http://master.php.net/manage/user-notes.php?action=reject+26931