Latest web development tutorials

PHP CSPRNG

PHP 7 新特性 PHP 7新特性

CSPRNG(Cryptographically Secure Pseudo-Random Number Generator,偽隨機數產生器)。

PHP 7 通過引入幾個CSPRNG 函數提供一種簡單的機制來生成密碼學上強壯的隨機數。

  • random_bytes() -加密生存被保護的偽隨機字符串。

  • random_int() -加密生存被保護的偽隨機整數。


random_bytes()

語法格式

string random_bytes ( int $length )

參數

  • length -隨機字符串返回的字節數。

返回值

  • 返回一個字符串,接受一個int型入參代表返回結果的字節數。

實例

實例

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

以上程序執行輸出結果為:

6f36d48a29

random_int()

語法格式

int random_int ( int $min , int $max )

參數

  • min -返回的最小值,必須是大於或等於PHP_INT_MIN 。

  • max -返回的最大值,必須是小於或等於PHP_INT_MAX 。

返回值

  • 返回一個指定範圍內的int型數字。

實例

實例

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

以上程序執行輸出結果為:

723
-64

PHP 7 新特性 PHP 7新特性