Best Method for Generated Random Seed in @php_net


If you use randoms in PHP you will want to seed it; this is example of the best possible method for making a random seed with one line of code for mt_srand + srand the two commands for seeding the random generation functions.

The following code is for mt_srand():

<?php

mt_srand((float)(mt_rand(-microtime(true) * time(), microtime(true) * time()) . ‘.’ . mt_rand(0, microtime(true) * time())));
mt_srand((float)(mt_rand(-microtime(true) * time() * time(), microtime(true) * time() * time()) . ‘.’ . mt_rand(0, microtime(true) * time() * time())));
mt_srand((float)(mt_rand(-microtime(true) * time() * time() * time(), microtime(true) * time() * time() * time()) . ‘.’ . mt_rand(0, microtime(true) * time() * time() * time())));
mt_srand((float)(mt_rand(-microtime(true) * time() * time() * time() * time(), microtime(true) * time() * time() * time() * time()) . ‘.’ . mt_rand(0, microtime(true) * time() * time()  * time() * time())));

?>

If you remember to seed your random before using mt_rand($min, $max); which is the better random selector that came with PHP5+. If your using earlier version of PHP you would use the following routine.

The following code is for srand() for seeding for rand($min, $max):

<?php

srand(floatval(rand(-microtime(true) * time(), microtime(true) * time()) . ‘.’ . rand(0, microtime(true) * time()));
srand(floatval(rand(-microtime(true) * time() * time(), microtime(true) * time() * time()) . ‘.’ . rand(0, microtime(true) * time() * time())));
srand(floatval(rand(-microtime(true) * time() * time() * time(), microtime(true) * time() * time() * time()) . ‘.’ . rand(0, microtime(true) * time() * time() * time())));
srand(floatval(rand(-microtime(true) * time() * time() * time() * time(), microtime(true) * time() * time() * time() * time()) . ‘.’ . rand(0, microtime(true) * time() * time()  * time() * time())));

?>

The same code is also usable with the lesser random function that is older ‘srand()’ you can also increase the range by added * time() to the routine…

Advertisements