Generate a secure random token in PHP
Create unpredictable tokens for password resets, API keys and CSRF protection with random_bytes.
- PHP
- GreenSnippets
- MIT
- Executed with PHP 8.2
<?php
function generateToken(int $bytes = 32): string
{
return rtrim(strtr(base64_encode(random_bytes($bytes)), '+/', '-_'), '=');
}
function hashToken(string $token): string
{
return hash('sha256', $token);
}Example / expected output
$token = generateToken(); // e.g. "kP3v...-url-safe"
$stored = hashToken($token); // save this, send $token to the userHow it works
Never use rand(), mt_rand() or uniqid() for secrets. random_bytes() reads from the operating system's cryptographically secure generator. Store only a hash of tokens that grant access (for example in password-reset tables) and compare with hash_equals.
Related snippets
- JavaScript Tested
Generate secure random IDs and integers
Create UUIDs, random integers in a range and URL-safe tokens with the Web Crypto API instead of Math.random.
- PHP Tested
Validate emails and URLs in PHP
Use filter_var to validate email addresses and http(s) URLs, with an allow-list for schemes.
- Python Tested
Sign API requests with HMAC-SHA256
Create and verify a timestamped signature over the method, path and body so requests cannot be forged or replayed.
- PHP Tested
Escape output to prevent XSS in PHP
A short helper around htmlspecialchars with the right flags for HTML text and attribute values.

