Skip to content

Instantly share code, notes, and snippets.

@jrobinsonc
Last active December 12, 2020 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrobinsonc/ef4245a6e915a038f108e12980ac24bc to your computer and use it in GitHub Desktop.
Save jrobinsonc/ef4245a6e915a038f108e12980ac24bc to your computer and use it in GitHub Desktop.
Generate random passwords.
<?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