Last active
December 12, 2020 17:08
-
-
Save jrobinsonc/ef4245a6e915a038f108e12980ac24bc to your computer and use it in GitHub Desktop.
Generate random passwords.
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 | |
/** | |
* Generate random password | |
* | |
* @see <https://gist.github.com/jrobinsonc/ef4245a6e915a038f108e12980ac24bc> | |
* @param int $len Number of characters the password should have. | |
* @param string $types Types of characters the password should have. | |
* Options are: l for lowercase, u for uppercase, d for digital, s for special. | |
* @return string | |
*/ | |
function randomPassword($len, $types = 'luds') | |
{ | |
$charsTypes = [ | |
'l' => 'abcdefghijklmnopqrstuvwxyz', | |
'u' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', | |
'd' => '1234567890', | |
's' => '@#$%&()_+!~\/:;-*?', | |
]; | |
$password = ''; | |
$typesArr = str_split($types); | |
while (strlen($password) < $len) { | |
$type = current($typesArr); | |
$charsList = $charsTypes[$type]; | |
$randomCharNum = mt_rand(0, strlen($charsList) - 1); | |
$password .= $charsList[$randomCharNum]; | |
if (! next($typesArr)) { | |
reset($typesArr); | |
} | |
} | |
return str_shuffle($password); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment