Skip to main content
Blue Moose logo Blue Moose Field notes
← All articles
php

Readable invite codes with Random\Randomizer

Lines of code on a dark screen

Every beta signup form I've built ends up needing the same small thing: a short invite code a human can read out over a call. My first attempts used substr(md5(uniqid()), 0, 8), which gave me codes full of 0/O and 1/l lookalikes, and nothing in it was cryptographically random. PHP 8.3 added a method that fixes both problems in one call: Random\Randomizer::getBytesFromString().

What the method actually does

According to the PHP manual, the signature is public function getBytesFromString(string $string, int $length): string, added in 8.3.0. It picks $length bytes at random from the string you pass in, with replacement. It throws a ValueError if the alphabet is empty or the length is below 1.

Two details matter. A new Randomizer() with no argument uses the secure engine, so the output is suitable for codes that guard something. And selection is weighted by how often a byte appears in your alphabet, so keep every character in it exactly once if you want a uniform distribution. It also works on bytes, so stick to ASCII.

A generator with an injectable engine

I wrapped it in a small readonly-friendly class. The alphabet drops the confusing characters (I, L, O, 0, 1), leaving 31 symbols. Ten characters gives 3110, roughly 8.2 × 1014 combinations.

<?php

declare(strict_types=1);

namespace Drupal\my_module;

use Random\Randomizer;

final class InviteCodeGenerator {

  private const ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';

  public function __construct(
    private readonly Randomizer $randomizer = new Randomizer(),
  ) {}

  public function generate(int $length = 10, int $groupSize = 5): string {
    $raw = $this->randomizer->getBytesFromString(self::ALPHABET, $length);
    return implode('-', str_split($raw, $groupSize));
  }

}

The default-value new Randomizer() in a constructor parameter is legal since PHP 8.1. In Drupal you can register the class as a service with no arguments and let that default kick in, or inject a custom Randomizer when you need one.

Making it deterministic in tests

The reason I inject the Randomizer rather than calling a static helper is testing. Give it a seeded Random\Engine\Mt19937 and the output is repeatable. I ran the class above on PHP 8.3.6 with seed 42 twice and got G7BW8-MN7DC both times, while an unseeded instance produced a different code.

<?php

use Drupal\my_module\InviteCodeGenerator;
use PHPUnit\Framework\TestCase;
use Random\Engine\Mt19937;
use Random\Randomizer;

final class InviteCodeGeneratorTest extends TestCase {

  public function testSeededOutputIsStable(): void {
    $a = new InviteCodeGenerator(new Randomizer(new Mt19937(42)));
    $b = new InviteCodeGenerator(new Randomizer(new Mt19937(42)));
    $this->assertSame($a->generate(), $b->generate());
  }

  public function testNoLookalikeCharacters(): void {
    $code = (new InviteCodeGenerator())->generate(200, 200);
    $this->assertDoesNotMatchRegularExpression('/[ILO01]/', $code);
  }

}

One caveat: the exact string a given seed yields is not something to hard-code in an assertion across PHP versions. Assert properties (length, alphabet, equality between two identically seeded instances) instead.

When not to use it

Random codes can collide. With a million live codes in the space above, the chance of a clash on any one new code is about 1 in 8 × 108, tiny but not zero, so keep a unique constraint on the column and retry on a violation. And never use a seeded Mt19937 outside tests: it is predictable by design. For anything longer-lived than an invite, such as password-reset or API tokens, I'd skip the human-friendly alphabet and use random_bytes() with a much longer value.

BM
Blue Moose
The moose behind Blue Moose. Full-stack PHP developer — Drupal by day, Symfony by night, tests always.