In PHP 7, following two new functions are introduced to generate cryptographically secure integers and strings in a cross platform way.
random_bytes() − Generates cryptographically secure pseudo-random bytes.
random_int() − Generates cryptographically secure pseudo-random integers.
random_bytes() generates an arbitrary-length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors.
string random_bytes ( int $length )
length − The length of the random string that should be returned in bytes.
Returns a string containing the requested number of cryptographically secure random bytes.
If an appropriate source of randomness cannot be found, an Exception will be thrown.
If invalid parameters are given, a TypeError will be thrown.
If an invalid length of bytes is given, an Error will be thrown.
<?php $bytes = random_bytes(5); print(bin2hex($bytes)); ?>
It produces the following browser output −
54cc305593
random_int() generates cryptographic random integers that are suitable for use where unbiased results are critical.
int random_int ( int $min , int $max )
min − The lowest value to be returned, which must be PHP_INT_MIN or higher.
max - The highest value to be returned, which must be less than or equal to PHP_INT_MAX.
Returns a cryptographically secure random integer in the range min to max, inclusive.
If an appropriate source of randomness cannot be found, an Exception will be thrown.
If invalid parameters are given, a TypeError will be thrown.
If max is less than min, an Error will be thrown.
<?php print(random_int(100, 999)); print(""); print(random_int(-1000, 0)); ?>
It produces the following browser output −
614 -882