Make a nice random string in PHP

Aug 28, 2020 PHP random string

How to make a random string that is cryptographically strong.

There are various other methods, but I tried using openssl_random_pseudo_bytes() for the time being.

/**
 * Generate random string with specified number of digits
 * (Old environments may not be cryptographically strong, but most environments are fine)
 *
 * @param int $length Length of desired character string (number of digits)
 * @param string $chars List of characters you want to use for random string
 */
function randomstr($length, $chars)
{
    $retstr = ``;
    $data = openssl_random_pseudo_bytes($length);
    $num_chars = strlen($chars);
    for ($i = 0; $i <$length; $i++)
    {
        $retstr .= substr($chars, ord(substr($data, $i, 1)) %$num_chars, 1);
    }
    return $retstr;
}

// To generate a 16-digit string in the hexadecimal range
$rand1 = randomstr(16, '0123456789ABCDEF');
// When generating a 16-digit character string in the range of 32 decimal numbers (Base32)
$rand2 = randomstr(16,'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567');
// To generate a 16-digit character string in the case of alphanumeric characters
$rand3 = randomstr(16,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789');