Skip to content

Instantly share code, notes, and snippets.

@shoman4eg
Forked from tylerhall/strong-passwords.php
Last active September 2, 2021 01:32
Show Gist options
  • Save shoman4eg/780d4b73e781bb0e5b924a278bcc3933 to your computer and use it in GitHub Desktop.
Save shoman4eg/780d4b73e781bb0e5b924a278bcc3933 to your computer and use it in GitHub Desktop.
A user friendly, strong password generator PHP function.
<?PHP
// Generates a strong password of N length containing at least one lower case letter,
// one uppercase letter, one digit, and one special character. The remaining characters
// in the password are chosen at random from those four sets.
//
// The available characters in each set are user friendly - there are no ambiguous
// characters such as i, l, 1, o, 0, etc. This, coupled with the $add_dashes option,
// makes it much easier for users to manually type or speak their passwords.
//
function generateStrongPassword($length = 9, $availableSets = 'luds'): string
{
$sets = [
'l' => 'abcdefghjkmnpqrstuvwxyz',
'u' => 'ABCDEFGHJKMNPQRSTUVWXYZ',
'd' => '23456789',
's' => '!@#$%&*?',
];
$availableSets = str_split($availableSets);
$sets = array_filter($sets, fn($key) => in_array($key, $availableSets, true), ARRAY_FILTER_USE_KEY);
$password = '';
foreach ($sets as $set) {
$password .= $set[random_int(0, strlen($set) - 1)];
}
$all = implode('', $sets);
for ($i = 0; $i < $length - count($sets); $i++) {
$password .= $all[random_int(0, strlen($all) - 1)];
}
return str_shuffle($password);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment