(PHP 5 >= 5.3.0, PHP 7, PHP 8)
openssl_random_pseudo_bytes — 生成一個(gè)偽隨機字節串
$length
, bool &$crypto_strong
= ?): string
生成一個(gè)偽隨機字節串 string ,字節數由 length
參數指定。
通過(guò) crypto_strong
參數可以表示在生成隨機字節的過(guò)程中是否使用了強加密算法。返回值為false
的情況很少見(jiàn),但已損壞或老化的有些系統上會(huì )出現。
length
所需字節串的長(cháng)度,必須為正整數。PHP會(huì )試著(zhù)將該參數轉換為非空整數來(lái)使用它。
crypto_strong
如果傳遞到該函數中,將會(huì )保存為一個(gè) boolean 值來(lái)表明是否使用了“強加密”,如果被用于GPG和密碼之類(lèi)的將返回true
, 否則返回 false
成功,返回生成的字節串 string , 或者在失敗時(shí)返回 false
.
示例 #1 openssl_random_pseudo_bytes() 范例:
<?php
for ($i = -1; $i <= 4; $i++) {
$bytes = openssl_random_pseudo_bytes($i, $cstrong);
$hex = bin2hex($bytes);
echo "Lengths: Bytes: $i and Hex: " . strlen($hex) . PHP_EOL;
var_dump($hex);
var_dump($cstrong);
echo PHP_EOL;
}
?>
以上例程的輸出類(lèi)似于:
Lengths: Bytes: -1 and Hex: 0 string(0) "" NULL Lengths: Bytes: 0 and Hex: 0 string(0) "" NULL Lengths: Bytes: 1 and Hex: 2 string(2) "42" bool(true) Lengths: Bytes: 2 and Hex: 4 string(4) "dc6e" bool(true) Lengths: Bytes: 3 and Hex: 6 string(6) "288591" bool(true) Lengths: Bytes: 4 and Hex: 8 string(8) "ab86d144" bool(true)