Last active
April 7, 2020 15:03
-
-
Save f2r/971c896d7c6528b09fd10659087252c4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function generatePassword(int $nbCharacters): string { | |
static $characters = [ | |
'lower' => 'abcdefghijklmnopqrstuvwxyz', | |
'upper' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', | |
'number' => '0123456789', | |
'special' => '@#$%^&+=._-!', | |
]; | |
// Password must have at least one character of each type | |
$passwordComposition = array_keys($characters); | |
// We're filling out the list with random character types | |
$count = $nbCharacters - count($passwordComposition); | |
while ($count--) { | |
$passwordComposition[] = array_rand($characters); | |
} | |
// Shuffle the password composition order | |
shuffle($passwordComposition); | |
// Building password from password composition | |
$password = ''; | |
foreach ($passwordComposition as $type) { | |
$password .= $characters[$type][mt_rand(0, strlen($characters[$type]) - 1)]; | |
} | |
return $password; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment