Create randomized token with specific length

Create randomized token with specific length

Random token generation is one of those issues which comes up way to many times while coding. There are a lot of ways to solve it but the "random" part is the difficult one. With PHP 7 there is a new way with random_int() to generate a truly random token:

/**
 * Generate token with length
 *
 * @param int $length
 *
 * @return string
 */
public function generateToken($length)
{
    $allowedCharacters = '0123456789abcdefghijklmnopqrstuvwxyz';

    $token = '';
    $allowedCharactersLength = mb_strlen($allowedCharacters, '8bit') - 1;
    for ($i = 0; $i < $length; ++$i) {
        $token .= $allowedCharacters[random_int(0, $allowedCharactersLength)];
    }

    return $token;
}