PHP Generate Secure Random Passwords

Posted on February 19, 2019 at 1:15 pm

This simple PHP function can generate secure random passwords:

function generate_strong_password($length = 15, $symbols = array("!", "#", "=", "@", "+", "(")) 
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
 
    $charactersLength = strlen($characters);
 
    $randomString = '';
 
    // Generate the random alphanumeric string
    for ($i = 0; $i < $length; $i++) $randomString .= $characters[random_int(0, $charactersLength - 1)];
 
    // Make space for symbols by "cutting" the string
    $randomString = substr($randomString, 0, strlen($randomString)-count($symbols));
 
    foreach($symbols as $key)
    {
        // Insert each symbol at random position
        $randomString = substr_replace($randomString, $key, random_int(1, strlen($randomString)-1), 0);
    }
 
    return $randomString;
}

It uses random_int() that is cryptographically secure.

The desired password length should NEVER be less than 15 chars.

And it makes sure to insert symbols.

Receive updates via email

Other Posts

Updated Posts