Skip to content
GreenSnippets

Generate a secure random token in PHP

Create unpredictable tokens for password resets, API keys and CSRF protection with random_bytes.

PHP
<?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

Output
$token = generateToken();       // e.g. "kP3v...-url-safe"
$stored = hashToken($token);    // save this, send $token to the user

How 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.