-
-
Save compermisos/cf11aed742d2e1fbd994e083b4b0fa78 to your computer and use it in GitHub Desktop.
A user friendly, strong password generator PHP function.
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
#!/usr/bin/php | |
<?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. | |
// | |
// Note: the $add_dashes option will increase the length of the password by | |
// floor(sqrt(N)) characters. | |
function generateStrongPassword($length = 15, $add_dashes = false, $available_sets = 'luds') | |
{ | |
$sets = array(); | |
if(strpos($available_sets, 'l') !== false) | |
$sets[] = 'abcdefghjkmnpqrstuvwxyz'; | |
if(strpos($available_sets, 'u') !== false) | |
$sets[] = 'ABCDEFGHJKMNPQRSTUVWXYZ'; | |
if(strpos($available_sets, 'd') !== false) | |
$sets[] = '23456789'; | |
if(strpos($available_sets, 's') !== false) | |
$sets[] = '!@#$%&*?'; | |
$all = ''; | |
$password = ''; | |
foreach($sets as $set) | |
{ | |
$password .= $set[tweak_array_rand(str_split($set))]; | |
$all .= $set; | |
} | |
$all = str_split($all); | |
for($i = 0; $i < $length - count($sets); $i++) | |
$password .= $all[tweak_array_rand($all)]; | |
$password = str_shuffle($password); | |
if(!$add_dashes) | |
return $password; | |
$dash_len = floor(sqrt($length)); | |
$dash_str = ''; | |
while(strlen($password) > $dash_len) | |
{ | |
$dash_str .= substr($password, 0, $dash_len) . '-'; | |
$password = substr($password, $dash_len); | |
} | |
$dash_str .= $password; | |
return $dash_str; | |
} | |
//take a array and get random index, same function of array_rand, only diference is | |
// intent use secure random algoritn on fail use mersene twistter, and on fail use defaul array_rand | |
function tweak_array_rand($array){ | |
if (function_exists('random_int')) { | |
return random_int(0, count($array) - 1); | |
} elseif(function_exists('mt_rand')) { | |
return mt_rand(0, count($array) - 1); | |
} else { | |
return array_rand($array); | |
} | |
} | |
echo generateStrongPassword(); | |
echo "\n"; |
Thanks! it works as advertised 👍
Thank you. I used this password generator a lot and I implement this code to my website https://kloningspoon.com/passgen/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!