note 34383 added to function.mt-srand
| From: | fasaxc at yahoo dot co dot uk | Date: | Fri, 25 Jul 2003 13:01:14 +0000 |
| Subject: | note 34383 added to function.mt-srand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-52633@lists.php.net to get a copy of this message | ||
In fact, here's an even better function than the one below assuming your install provides a
random entropy daemon and you're running *nix (to check for the former type "head -c 6
/dev/urandom" on the command line if available - if you get 6 random characters you're
set). N.B. php must be able to find the head program so it must be in your path and allowed if
you're running safe mode.
The functions db_set_global() and db_get_global() I use to set/get a variable from a central
database but you could save/restore the variable from a file instead or just use the function
get_random_word().
<?
####################################
## returns a random 32bit integer.
## Passing a parameter of True gives a better random
## number but relies on the /dev/random device
## which can block for a long time while it gathers
## enough random data ie. DONT USE IT unless
## a) You have an entropy generator attatched to
## your computer set to /dev/random -OR-
## b) Your script is running locally and generating
## a good random number is very important
####################################
function get_random_word($force_random=False) {
if ($force_random) {
$u='';
} else {
$u='u';
}
$ran_string=shell_exec("head -c 4 /dev/{$u}random");
$random=ord(substr($ran_string,0,1))<<24 |
ord(substr($ran_string,1,1))<<16 |
ord(substr($ran_string,2,1))<<8 |
ord(substr($ran_string,3,1));
return $random;
}
--EITHER - IF YOU'VE SET UP A DATABASE OF GLOBAL VARIABLES--
## If the seed is found in the database
if ($seed=db_get_global('seed')) {
# use mt_rand() to get the next seed
mt_srand($seed);
# then XOR that with a random word
$seed=(mt_rand() ^ get_random_word());
} else {
## Make a completely new seed (First Run)
# Generate the seed as a proper random no using /dev/random
$seed=get_random_word(True);
mt_srand($seed);
}
db_set_global('seed',$seed);
--OR JUST--
mt_srand(get_random_word());
?>
----
Manual Page -- http://www.php.net/manual/en/function.mt-srand.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+34383
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+34383&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+34383&report=yes