random_bytes() returns raw random bytes suitable for secrets and other security-sensitive values. Encode the bytes when you need a printable token.
$token = bin2hex(random_bytes(16));
echo $token; // 32 hexadecimal charactersecho random_bytes($length);
$length : Length of the random string returned as bytes. $str=random_bytes(7);
echo bin2hex($str);
Output ( Refresh this page to to see how the random number changes )
20748ba694e1c9
<?php
$key = bin2hex(random_bytes(16)); // Generates a 32-character API key
echo "Generated API key: $key";
?>
<?php
$password = bin2hex(random_bytes(8)); // Generates a secure 16-character password
echo "Random password: $password";
?>
<?php
$salt = bin2hex(random_bytes(16)); // 16-byte random nonce
echo "Generated nonce: $salt";
?>
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.