Posted: Tue Jan 23, 2007 5:37 pm
Here is my version of a random key generator that uses the mt_getrandmax() as you described: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.
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;
}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>