PHP

Random Readable Token

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Generate a short, human-readable random token using an alphabet that omits look-alike characters (0/O, 1/l/I). Useful for invite codes, short-lived signin tokens, password reset codes — anything a human might type.
PHP
Raw
<?php
function readableToken(int $len = 8): string {
    // Crockford-style alphabet — no 0, O, 1, l, I, U
    $alpha    = 'ABCDEFGHJKMNPQRSTVWXYZ23456789';
    $alphaLen = strlen($alpha);
    $out      = '';
    for ($i = 0; $i < $len; $i++) {
        // Rejection sampling for uniform distribution.
        do { $b = ord(random_bytes(1)); } while ($b >= intdiv(256, $alphaLen) * $alphaLen);
        $out .= $alpha[$b % $alphaLen];
    }
    return $out;
}

echo readableToken(6);   // e.g. "K7TQ4N"
echo readableToken(12);  // e.g. "X3RJ8H2BVQ7K"
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.