- substr: documentation ( source)
- var_dump: documentation ( source)
- bin2hex: documentation ( source)
- hash: documentation ( source)
- ceil: documentation ( source)
- max: documentation ( source)
- hexdec: documentation ( source)
- pow: documentation ( source)
<?php
class PseudoRandomSequence {
const STATE_HASH = "sha512";
// 1/2 STATE_HASH block size,
const STATE_SIZE = 32;
private $state;
public function __construct($state) {
$this->state = $state;
$this->mixState();
}
public function int($min = 0, $max = PHP_INT_MAX) {
$range = $max - $min;
if ($range <= 0 || is_float($range)) {
throw new Exception("Invalid min/max provided");
}
$bits = 0;
$tmp = $range;
while ($tmp >>= 1) {
$bits++;
}
$bytes = (int) max(ceil($bits / 8), 1);
$mask = pow(2, $bits) - 1;
do {
$rand = $this->bytes($bytes);
$result = hexdec(bin2hex($rand)) & $mask;
} while ($result > $range);
return $result + $min;
}
public function bytes($n) {
$ret = '';
do {
$ret .= $this->mixState();
} while (strlen($ret) < $n);
return substr($ret, 0, $n);
}
private function mixState() {
$hash = hash(self::STATE_HASH, $this->state, true);
$this->state = $hash;
return substr($hash, self::STATE_SIZE);
}
}
$prng = new PseudoRandomSequence("blah");
for ($i = 0; $i < 100; $i++) {
var_dump($prng->int());
}