← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

random_bytes()

php PHP 7.0+ Intermediate

Also Known As

random_bytes() random_int() CSPRNG PHP

TL;DR

Generates cryptographically secure random bytes from the OS entropy source — use for tokens, salts, and nonces.

Explanation

random_bytes(int $length) returns a string of $length cryptographically random bytes sourced from /dev/urandom (Linux/macOS) or CryptGenRandom (Windows). bin2hex(random_bytes(32)) produces a 64-character hex token with 256 bits of entropy — unguessable in practice. Use it for password reset tokens, API keys, CSRF tokens, and any other security-sensitive random value. Never use rand(), mt_rand(), or uniqid() for these purposes.

Common Misconception

rand() and mt_rand() are sufficient for generating tokens and nonces. Both are seeded PRNGs predictable from enough observed output. random_bytes() pulls from the OS entropy pool and is the only correct choice for security-sensitive randomness in PHP.

Why It Matters

random_bytes() generates cryptographically secure random bytes using the OS entropy source — it is the correct foundation for tokens, salts, IVs, and any security-sensitive random value in PHP 7+.

Common Mistakes

  • Using rand(), mt_rand(), or array_rand() for security purposes — they are seeded by time and predictable.
  • Using uniqid() for tokens — it is based on microtime and has insufficient entropy.
  • Not hex-encoding or base64-encoding the output before storage — raw bytes may contain null bytes.
  • Requesting fewer bytes than needed — 16 bytes (128 bits) is the minimum for security tokens; 32 bytes (256 bits) is better.

Code Examples

✗ Vulnerable
// Predictable token generation:
$token = md5(uniqid(mt_rand(), true)); // Guessable — time-based entropy
$token = sha1(rand()); // rand() is not cryptographically secure

// Correct:
$token = bin2hex(random_bytes(32)); // 256 bits of CSPRNG entropy
✓ Fixed
// Cryptographically secure random bytes (PHP 7+)
$token = random_bytes(32);                    // 32 bytes = 256 bits
$hex   = bin2hex($token);                     // 64 hex chars
$b64   = base64_encode($token);               // URL-safe: strtr(base64_encode($token), '+/', '-_')

// Secure random integer (e.g. OTP, random delay)
$otp   = random_int(100000, 999999);          // cryptographically secure

// NOT cryptographically secure — never use for tokens/secrets:
// mt_rand(), rand(), array_rand(), shuffle() — all predictable

// Password reset token
$resetToken = bin2hex(random_bytes(32)); // store hash in DB, send raw to user
$stored     = hash('sha256', $resetToken);

Added 15 Mar 2026
Edited 22 Mar 2026
Views 28
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 1 ping S 1 ping M 1 ping T 0 pings W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 1 ping T 0 pings W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 1 ping T 0 pings W 0 pings T 1 ping F 0 pings S
No pings yet today
Amazonbot 7 Perplexity 4 Ahrefs 4 Unknown AI 2 Google 2 SEMrush 2
crawler 20 crawler_json 1
DEV INTEL Tools & Severity
🔴 Critical ⚙ Fix effort: Low
⚡ Quick Fix
Use random_bytes(32) for all cryptographic randomness — it reads from /dev/urandom on Linux and is guaranteed cryptographically secure; never use mt_rand(), rand(), or uniqid() for security
📦 Applies To
PHP 7.0+ web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
mt_rand() or rand() for token generation; uniqid() for session tokens; time()-based random seeds; md5(microtime()) as random token
Auto-detectable: ✓ Yes semgrep psalm phpstan
⚠ Related Problems
🤖 AI Agent
Confidence: High False Positives: Low ✓ Auto-fixable Fix: Low Context: Line
CWE-330 CWE-338

✓ schema.org compliant