Generating a random token for a mail confirmation link using PHP and Symfony

Published on 2023-07-01 • Modified on 2023-07-01

This snippet shows how to generate a random token for a mail confirmation link using PHP and Symfony. The final length of the generated string is the same (50). The result is slightly different with Symfony as the token has more "randomness" with uppercase letters and a better mix between letters and numbers.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\String\ByteString;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet263Trait
{
    public function snippet263(Request $request): void
    {
        // PHP
        $confirmationCode1 = bin2hex(random_bytes(25));
        $confirmationCode2 = bin2hex((new \Random\Randomizer())->getBytes(25));

        // Symfony
        $confirmationCode3 = ByteString::fromRandom(50);

        echo 'PHP: '.$confirmationCode1.' '.\strlen($confirmationCode1).PHP_EOL;
        echo 'PHP 8.2: '.$confirmationCode2.' '.\strlen($confirmationCode2).PHP_EOL;
        echo 'Symfony: '.$confirmationCode3.' '.$confirmationCode3->length();

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!