Skip to content

Instantly share code, notes, and snippets.

@adrienlucas
Created March 3, 2016 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adrienlucas/71657e2552dd239ec7a5 to your computer and use it in GitHub Desktop.
Save adrienlucas/71657e2552dd239ec7a5 to your computer and use it in GitHub Desktop.
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