Skip to content

Instantly share code, notes, and snippets.

@f2r
Last active April 7, 2020 15:03
Show Gist options
  • Save f2r/971c896d7c6528b09fd10659087252c4 to your computer and use it in GitHub Desktop.
Save f2r/971c896d7c6528b09fd10659087252c4 to your computer and use it in GitHub Desktop.
<?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