How to Generate Random String Token in PHP

In PHP, you can use the random_bytes function to generate secure random bytes, which is available in PHP 7.0 and later versions. Here is an example of a PHP function that emulates the functionality of the JavaScript function you provided:

<?php

function generateToken(int $length, array $options = []): string {
    $uppercase = isset($options['uppercase']) ? $options['uppercase'] : true;
    $lowercase = isset($options['lowercase']) ? $options['lowercase'] : true;
    $numbers = isset($options['numbers']) ? $options['numbers'] : true;

    $charset = '';
    if ($uppercase) $charset .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    if ($lowercase) $charset .= 'abcdefghijklmnopqrstuvwxyz';
    if ($numbers) $charset .= '0123456789';

    if (strlen($charset) === 0) {
        throw new InvalidArgumentException('At least one character set must be selected.');
    }

    $token = '';
    for ($i = 0; $i < $length; $i++) {
        $randomIndex = random_int(0, strlen($charset) - 1);
        $token .= $charset[$randomIndex];
    }

    return $token;
}

// Example usage:
try {
    $token = generateToken(16, ['uppercase' => true, 'lowercase' => true, 'numbers' => true]);
    echo "Generated token: " . $token;
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>

In this PHP function, generateToken accepts two parameters: $length (the length of the token) and an $options array, which contains configurations for whether to include uppercase letters, lowercase letters, and numbers. Inside the function, a character set $charset is constructed, and then the random_int function is used to generate secure random integers as indices. For each character of the token, a random index is generated and used to select a character from $charset.

Please note that random_int was introduced in PHP 7.0 and later, providing better randomness than rand and mt_rand, and is cryptographically secure. If your PHP version is lower than 7.0, you might need to use the mt_rand function, but please remember that it is not as secure as random_int.

In the example usage, we call the generateToken function and print the generated token. If an error occurs, such as not selecting any character set, the function will throw an InvalidArgumentException.