3v4l.org

run code in 300+ PHP versions simultaneously
<?php if (!function_exists('random_bytes')) { function random_bytes($size) { if(!is_int($size)) throw new InvalidArgumentException('random_bytes: $size must be an int'); if($size < 0) throw new InvalidArgumentException('random_bytes: $size must not be negative'); //if(function_exists('mcrypt_create_iv')) //{ // $result = mcrypt_create_iv($size, MCRYPT_DEV_URANDOM); //} else if(function_exists('openssl_random_pseudo_bytes')) { $result = openssl_random_pseudo_bytes($size, $isSecure); if($isSecure !== true) { throw new RuntimeException("random_bytes: openssl_random_pseudo_bytes returned insecure data"); } } else { throw new RuntimeException("random_bytes: No RNG found"); } if(!is_string($result) || (strlen($result) !== $size)) { throw new RuntimeException("random_bytes: RNG is unavailable or broken"); } return $result; } } if (!function_exists('random_int')) { function random_int($min, $max) { if(!defined('PHP_INT_SIZE')) trigger_error("random_int: This version of PHP is not supported", E_USER_ERROR); if(!is_int($min)) throw new InvalidArgumentException('random_int: $min must be an int'); if(!is_int($min)) throw new InvalidArgumentException('random_int: $min must be an int'); if($min > $max) throw new InvalidArgumentException('random_int: $min must be less or equal to $max'); $range = $max - $min + 1; // the rejection probability is at most 0.5, so this corresponds to a failure probability of 2^-128 for a working RNG for($attempts = 0; $attempts < 128; $attempts++) { // generate a random integer $bytes = random_bytes(PHP_INT_SIZE); $value = 0; for($i = 0; $i < PHP_INT_SIZE; $i++) { $value = ($value << 8) | ord($bytes[$i]); } if(!is_int($range)) { if(($value >= $min) && ($value <= $max)) { return $value; } } else { $value &= PHP_INT_MAX; // equivalent to (PHP_INT_MAX + 1) % range, but avoids int overflows // I'm assuming PHP_INT_MAX + 1 is a power-of-two $reject = (-$range & PHP_INT_MAX) % $range; if($value >= $reject) { return ($value % $range) + $min; } } } throw new RuntimeException("random_int: RNG is broken - too many rejections"); } } random_int(0, 1000);

preferences:
40.58 ms | 402 KiB | 5 Q