Skip to content

Instantly share code, notes, and snippets.

@alexseif
Forked from yoga-/randomPassword.php
Created March 5, 2020 05:48
Show Gist options
  • Save alexseif/fcffd284e4823a6a96ea9f3baabead80 to your computer and use it in GitHub Desktop.
Save alexseif/fcffd284e4823a6a96ea9f3baabead80 to your computer and use it in GitHub Desktop.
PHP random password generator - contains at least one lower case letter, one upper case letter, one number and one special character,
//generates a random password of length minimum 8
//contains at least one lower case letter, one upper case letter,
// one number and one special character,
//not including ambiguous characters like iIl|1 0oO
function randomPassword($len = 8) {
//enforce min length 8
if($len < 8)
$len = 8;
//define character libraries - remove ambiguous characters like iIl|1 0oO
$sets = array();
$sets[] = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
$sets[] = 'abcdefghjkmnpqrstuvwxyz';
$sets[] = '23456789';
$sets[] = '~!@#$%^&*(){}[],./?';
$password = '';
//append a character from each set - gets first 4 characters
foreach ($sets as $set) {
$password .= $set[array_rand(str_split($set))];
}
//use all characters to fill up to $len
while(strlen($password) < $len) {
//get a random set
$randomSet = $sets[array_rand($sets)];
//add a random char from the random set
$password .= $randomSet[array_rand(str_split($randomSet))];
}
//shuffle the password string before returning!
return str_shuffle($password);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment