Function name: random_bytes()
Applicable version: PHP 7.0.0 and above
Function description: The random_bytes() function is used to generate a random byte string of specified length. This function generates random bytes using the cryptographically secure pseudo-random number generator provided by the operating system.
Syntax: random_bytes(int $length): string|false
parameter:
- $length: The length of the generated random byte string, expressed in bytes. Must be a positive integer.
Return value:
- Returns a string containing random bytes, or returns false when the generation fails.
Example:
// 生成一个包含10个字节的随机字节串$randomBytes = random_bytes(10); // 打印随机字节串的16进制表示echo bin2hex($randomBytes);
The above example outputs a hexadecimal representation of a random byte string similar to the following:
d6f5389e1b6a85c0c9
Notes:
- The random_bytes() function relies on the cryptographically secure pseudo-random number generator provided by the operating system. Therefore, the strength of the generated random byte string depends on the quality of the random number generator of the operating system.
- The generated random byte string may contain any bytes, including control characters and non-print characters. When processing random byte strings, be careful to ensure that there is no security problem or unexpected behavior.
- On some operating systems, calling of the random_bytes() function may be blocked if there is not enough entropy available to generate random bytes. In this case, consider using the random_int() function to generate a random integer and converting it into a byte string using the pack() function.
Reference documentation: https://www.php.net/manual/en/function.random-bytes.php