Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
True Random in PHP
<?php
/**
* Generate a true random integer.
* To be used as a rand() replacement as it behave exactly the same.
*
* int true_rand(void)
* int true_rand(int $min, int $max)
*
* It uses the HotBits webservice from FourmilLab as randomness provider
* based on radioactive decay. See https://www.fourmilab.ch/hotbits/.
*/
function true_rand($min=0, $max=null)
{
$max = $max ?: getrandmax();
$r = $max + 1 - $min;
return abs(hexdec(bin2hex(file_get_contents(sprintf('https://www.fourmilab.ch/cgi-bin/Hotbits?nbytes=%d&fmt=bin&npass=1&lpass=8&pwtype=3', strlen(dechex($r)))))) % $r) + $min;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment