Created
March 3, 2016 13:44
-
-
Save adrienlucas/71657e2552dd239ec7a5 to your computer and use it in GitHub Desktop.
True Random in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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