random value (used in phpBB)

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

User avatar
WaldoMonster
Forum Contributor
Posts: 225
Joined: Mon Apr 19, 2004 6:19 pm
Contact:

Post by WaldoMonster »

feyd wrote:What I typically will do is use mt_rand() with mt_getrandmax() to build a decimal value. I then multiply the decimal value by the end scale to reach the actual value. It will have rounding errors for very large ranges, but that's fairly unless you have access to even better random streams.
Here is my version of a random key generator that uses the mt_getrandmax() as you described:

Code: Select all

function random()
{
$key        = '';
$list       = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$maxIndex   = strlen($list) - 1;
$maxRand    = mt_getrandmax();
for ($i = 0; $i < 40; $i++)
    {
    $index = round(mt_rand(0, $maxRand) * $maxIndex / $maxRand);
    $key .= $list[$index];
    }
return $key; 
}
PS
When using both lower and uppercase characters be aware to use BINARY compare in a MySQL database.

<update>
BINARY compare can be very slow.
viewtopic.php?t=62163
</update>
Post Reply