PHP | random_bytes () Function Last Updated : 11 Jul, 2025 Comments Improve Suggest changes 1 Likes Like Report 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 <?php //random_bytes () function in PHP $length = random_bytes('4'); //Print the result and convert by binaryhexa var_dump(bin2hex($length)); ?> Output:string(8) "e62a94a2" php <?php //random_bytes () function in PHP $length = random_bytes('6'); //Print the result and convert by binaryhexa var_dump(bin2hex($length)); ?> Output: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: https://www.php.net/manual/en/function.random-bytes.php Create Quiz Comment J jit_t Follow 1 Improve J jit_t Follow 1 Improve Article Tags : Web Technologies PHP Explore PHP Tutorial 8 min read BasicsPHP Syntax 4 min read PHP Variables 5 min read PHP | Functions 8 min read PHP Loops 4 min read ArrayPHP Arrays 5 min read PHP Associative Arrays 4 min read Multidimensional arrays in PHP 5 min read Sorting Arrays in PHP 4 min read OOPs & InterfacesPHP Classes 2 min read PHP | Constructors and Destructors 5 min read PHP Access Modifiers 4 min read Multiple Inheritance in PHP 4 min read MySQL DatabasePHP | MySQL Database Introduction 4 min read PHP Database connection 2 min read PHP | MySQL ( Creating Database ) 3 min read PHP | MySQL ( Creating Table ) 3 min read PHP AdvancePHP Superglobals 6 min read PHP | Regular Expressions 12 min read PHP Form Handling 4 min read PHP File Handling 4 min read PHP | Uploading File 3 min read PHP Cookies 9 min read PHP | Sessions 7 min read Like