PHP Password Generator Snippet

in PHP

Get stuck trying to pick a new password each time you signup to a new service or website. Most people do use the same password on every site that they go to but this can be dangerous if 1 site gets hacked then your password could be used on all the sites you regularly use.

Therefore for best security reason you should use a different password for different websites and there are many password management tools out there that can help you remember all your passwords. So if you are having to think up new passwords each time you sign up to a website you might run out of ideas of what to put and start creating just anything. But some websites have password strength requirements, such as it has to have at least one number, or one capital letter.

Password Strength

The below php snippet will generate a password for you and you can customise it to a certain level of password strength.

If the strength is more than 1 then capitals are included.

If the strength is more than 2 then capital vowels are included.

If the strength is more than 4 then numbers are included.

Finally if the strength is more than 8 then special characters are included.

I find that a password strength of more then 4 is good enough for most websites.

function generatePassword($length=9, $strength=0) { $vowels = 'aeuy'; $consonants = 'bdghjmnpqrstvz'; if ($strength >= 1) { $consonants .= 'BDGHJLMNPQRSTVWXZ'; } if ($strength >= 2) { $vowels .= "AEUY"; } if ($strength >= 4) { $consonants .= '23456789'; } if ($strength >= 8 ) { $vowels .= '@#$%'; }

$password = ''; $alt = time() % 2; for ($i = 0; $i < $length; $i++) { if ($alt == 1) { $password .= $consonants[(rand() % strlen($consonants))]; $alt = 0; } else { $password .= $vowels[(rand() % strlen($vowels))]; $alt = 1; } } return $password; } [/php]

Subscribe To Newsletter

Get weekly updates to your email