PHP CSPRNG

PHP 7 新特性PHP 7 New Features

CSPRNG (Cryptographically Secure Pseudo-Random Number Generator, pseudo-random number generator).

PHP 7 provides a simple mechanism for generating cryptographically strong random numbers by introducing several CSPRNG functions.

  • random_bytes()- Randomly generate strings.

  • random_int()- Randomly generate integers.


random_bytes()

Syntax

string random_bytes ( int $length )

Parameters

  • length- The number of bytes to return for the random string.

Return Value

  • Returns a string, accepting an int parameter representing the number of bytes in the returned result.

Example

Example

<?php
$bytes
= random_bytes(5);
print(
bin2hex($bytes));
?>

The output of the above program is:

6f36d48a29

random_int()

Syntax

int random_int ( int $min , int $max )

Parameters

  • min- The minimum value to return, must be greater than or equal to PHP_INT_MIN.

  • max- The maximum value to return, must be less than or equal to PHP_INT_MAX.

Return Value

  • Returns an int within the specified range.

Example

Example

<?php
print(random_int(100, 999));
print(
PHP_EOL);
print(
random_int(-1000, 0));
?>

The output of the above program is:

723
-64

PHP 7 新特性PHP 7 New Features

Other Extensions