Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A user friendly, strong password generator PHP function.
// 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 = 9, $add_dashes = false, $available_sets = 'luds')
$sets = array();
if(strpos($available_sets, 'l') !== false)
$sets[] = 'abcdefghjkmnpqrstuvwxyz';
if(strpos($available_sets, 'u') !== false)
if(strpos($available_sets, 'd') !== false)
$sets[] = '23456789';
if(strpos($available_sets, 's') !== false)
$sets[] = '!@#$%&*?';
$all = '';
$password = '';
foreach($sets as $set)
$password .= $set[array_rand(str_split($set))];
$all .= $set;
$all = str_split($all);
for($i = 0; $i < $length - count($sets); $i++)
$password .= $all[array_rand($all)];
$password = str_shuffle($password);
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;

PetterS commented May 8, 2012

It would be more "user friendly" if it generated passwords from a list of words. :-)

Excellent - thank you!

Thank you.

witul commented Aug 20, 2014

Thanks :)

Great. Thanks!

jabaru commented Nov 20, 2014


thx a lot!!

Great Code

Good work, thanks for the function

kildeby commented Jun 30, 2015

I can't seem to make it display the password? How do I use it?

  • nevermind, I found out. Just sharing -> add:

@Shifrin: Your solution does not require a BIG LETTER, a small letter, a number (0-9) and a special character, which makes your password very much stronger.

Head's up: This gist is not secure. Neither array_rand() nor str_shuffle() are cryptographically secure.

Recommended reading: How to generate secure passwords in PHP.

This is great! I needed the ability to force the use of certain characters to make the password. hanks! Good work!



God bless you!

hsali commented Oct 23, 2016

a good script.

0ngsh commented Nov 8, 2016

Thanks,Very Useful

Good work!

AlkarE commented Jun 9, 2017

Thanks a lot!


A very good script. Thank you so much.

thank you 👍

SigmaOne commented Nov 20, 2017

Thank you dude! here)

thank you


make a forked version of this script, whit some improvments in crypt functions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment