Generate Random Number with PHP Using /dev/urandom

email-addthis printer-addthis favorites-addthis facebook-addthis digg-addthis | Share

23 Apr 2010 09:14:33
Category: PHP Development

I found lots of people on the inter-tubes saying use /dev/urandom to generate a better random number. But couldn't find examples of how this was done using PHP. But I figured it out so here's how I do it.

function getRandom($min, $max) 
    $bits = '';

    $diff = $max-$min;
    $bytes = ceil($diff/256);

    $fp = @fopen('/dev/urandom','rb');
    if ($fp !== FALSE) {
        $bits .= @fread($fp,$bytes);
    $bitlength = strlen($bits);
    for ($i = 0; $i < $bitlength; $i++) {
        $int =  1+(ord($bits[$i]) % (($max-$min)+1));
    return $int;
echo getRandom(1, 20);

Use of /dev/urandom decreases the likely hood that a random number created at the same time will be duplicate. mt_rand is still good for most things. Of course I'm making no claim that the above code is cryptographically secure.

In speed tests I found that /dev/urandom was much much slower then using mt_rand(). But speed is not why you use /dev/urandom.