The random_bytes()is an inbuilt function in PHP. The main function is to generate cryptographically secure pseudo-random bytes. It generates cryptographic random bytes of arbitrary string length.
The different sources of randomness used in this function, they are as follows:-
- Window : CryptGenRandom() function.
- Linux : getrandom(2) system call function.
Syntax :
String random_bytes ( int $length )
Parameter :
It is the length of random string, returned in bytes.
Return Value: The function returns the cryptographically secure random bytes in string.
Examples:
Input : length = 7 Output :string(14) "cbd392c01352b0"
Below programs illustrate the random_bytes () function in PHP.
Program 1:
<?php //random_bytes () function in PHP $length = random_bytes('4'); //Print the reult and convert by binaryhexa var_dump(bin2hex($length)); ?> |
string(8) "e62a94a2"
<?php //random_bytes () function in PHP $length = random_bytes('6'); //Print the reult and convert by binaryhexa var_dump(bin2hex($length)); ?> |
string(12) "808fc44d325b"
Exception Error :
- Invalid parameter will give TypeError .
- Invalid length of bytes gives Error.
- If source of randomness is not found then Exception will be thrown.
References:
http://php.net/manual/en/function.random-bytes.php
Recommended Posts:
- How to get the function name inside a function in PHP ?
- PHP 5 vs PHP 7
- PHP | Get PHP configuration information using phpinfo()
- PHP | php.ini File Configuration
- How to import config.php file in a PHP script ?
- PHP | imagecreatetruecolor() Function
- PHP | ImagickDraw getTextAlignment() Function
- PHP | Ds\Sequence last() Function
- PHP | Imagick floodFillPaintImage() Function
- Function to escape regex patterns before applied in PHP
- PHP | array_udiff_uassoc() Function
- PHP | geoip_continent_code_by_name() Function
- PHP | GmagickPixel setcolor() function
- PHP | opendir() Function
- PHP | cal_to_jd() Function
- PHP | stream_get_transports() Function
- PHP | Ds\Deque pop() Function
- PHP | SimpleXMLElement children() Function
- PHP | array_intersect_ukey() Function
- PHP | is_numeric() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

