random_bytes to generate cryptographically secure random bytes

Generate cryptographically secure random bytes

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 characters
echo random_bytes($length);
$length : Length of the random string returned as bytes.

Generates cryptographically secure random bytes that can be used for secrets, tokens, keys and nonces.
Available in PHP 7 and PHP 8.

Example

$str=random_bytes(7);
echo bin2hex($str);
Output ( Refresh this page to to see how the random number changes )
20748ba694e1c9

Example 1: Generating Cryptographically Secure API Keys

<?php
$key = bin2hex(random_bytes(16));  // Generates a 32-character API key
echo "Generated API key: $key";
?>

Example 2: Creating Random Passwords

<?php
$password = bin2hex(random_bytes(8));  // Generates a secure 16-character password
echo "Random password: $password";
?>

Example 3: Generating a random nonce

<?php
$salt = bin2hex(random_bytes(16));  // 16-byte random nonce
echo "Generated nonce: $salt";
?>

String Functions how to change all the letters to upper case nl2br() To add Line break


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer