PHP Code Examples

Generate a Secure Random Token in PHP

Create cryptographically secure random tokens for verification links, password resets, and one-time actions.

Example

<?php
$token = bin2hex(random_bytes(32));

// Store a hash of the token in the database.
$tokenHash = hash('sha256', $token);

// Send the original token to the user in a one-time link.
// Example: https://example.com/verify?token=...

Explanation

random_bytes() uses a cryptographically secure source. A 32-byte value becomes a 64-character hexadecimal token.

Store only the token hash where practical. When the user returns with the token, hash the submitted value and compare it with the stored hash using hash_equals().

Good practice

Set an expiry time, make tokens single-use, and invalidate them after successful verification.

Share this page Help other developers discover this resource.