Last active
September 15, 2023 19:37
-
-
Save yoga-/8c2c196173be3d4aff56 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,
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
//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); | |
} |
Sorry but as good as it look like, this is not a good practice at all for a secure PHP password generator. As said on the PHP documentation :
It uses a pseudo random number generator that is not suitable for cryptographic purposes.
Link
So, this is a good base, but still, not safe nor secure.
I know it's an old code but it still well referenced... So in the current state, it's not good if some new programmers use it just like that.
Edit : Here is a code quite close to this one, but improved on crypt functions :
https://gist.github.com/compermisos/cf11aed742d2e1fbd994e083b4b0fa78
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
good one