A trap about PHP random number

  ffb        2013-06-07 09:10:10       11,819        0    

The method to get random number in PHP is very simple, we only need to use rand() function.

int rand ( int $min , int $max )  

One function call can return the random number in a specified range. But in fact, the random number in computer is actually pseudorandomness, generally to increase the randomness, we may set a random seed before calling rand().

void srand ([ int $seed ] )  

According to other language features, we should pass a time value as a parameter to the srand() function, generally we may pass millisecond or microsecond. Starting from PHP 4.2, srand() will be automatically called when calling rand(), so now we may no need to call srand() explicitly.

In PHP, we can use microtime() function to get the random number, so in an ordinary scene, we can use below codes to get random number:After executing above codes, we will get two random numbers, it seems everything is fine. But if we execute them again, we may find the random number generated are the same as the first time.

<?php 
    srand(microtime()); 
    echo rand(1, 25).PHP_EOL; 
    echo rand(1, 25).PHP_EOL; 
?>

What happened? We have set the srand() with the microsecond time.

By checking the document, We find microtime() returns a string in the form "msec sec", where sec is the current time measured in the number of seconds since the Unix epoch (0:00:00 January 1, 1970 GMT), and msec is the number of microseconds that have elapsed since sec expressed in seconds.

Since PHP 5, we can pass a parameter $get_as_float, If get_as_float is set to TRUE, then microtime() returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.

 

We call it twice continuously and we get different random numbers, so let's write a bash script:

for i in $(seq 1 1 100)  
do  
    curl http://127.0.0.1/rnd.php  
    echo   
done  

And let it run 100 times, we can get the results expected. Actually the above example will report:

PHP Notice: A non well formed numeric value encountered

Or

We can use a mt_rand() function to replace the old rand() function, the efficiency of mt_rand() is 4 times higher than rand().

Source : http://blog.csdn.net/ffb/article/details/9039043

PHP  RAND  SRAND  MT_RAND 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

Blue screen will die when Windows dies