Solid random number generator function for PHP

So, PHP’s random number generation is pretty weak- it uses the rand() function which is positively atrocious for anything more than playing a guessing game. So, I wrote the following to give me something a bit better- maybe someone else can use it too (and it’s fast). The good thing is if it can’t read /dev/urandom, it’ll fall back to the mediocre mt_rand() function:

public function random($min = 0, $max = 0) {
   $response = 0;

   if (($fd = fopen("/dev/urandom", "rb")) !== FALSE) {
      # 32 bits of data
      $read_len = 4;

      # MD5 is probably not needed, but whatever.
      $random = md5(fread($fd, $read_len), TRUE);
      fclose($fd);

      $val = 0;
      for($i = $read_len - 1; $i >= 0; $i--) {
         $ch = substr($random, $i, 1);
         $val = ($val << 8 ) | ord($ch);
      }

      $response = ($val % ($max - $min + 1)) + $min;
   } else
      $response = mt_rand($min, $max);

   return $response;
}

One Response to “Solid random number generator function for PHP”

  1. Ross Bonner Says:

    I’m not a PHP guy, but wouldn’t you have to do a abs() function on $val in case it was negative? Also, I think …

    $temp = unpack(”V”, $random);
    $val = $temp[1];

    might be faster than the for loop.

Leave a Reply

You must be logged in to post a comment.