When it comes to protecting web user accounts, the first step is to ask users for a strong password, one composed of 10-12 lowercased, uppercased, numeric, and special characters.
The length and complexity of a password have its importance not just because it may be hard to guess but mainly because of the resistance against brute force attacks (conducted on a compromised database - like one leaked from 123rf.com, or directly against login forms).
So we ask for a strong password from users, but what if we want to help them with a random password that respects the same password strength rules?
Here comes in handy the bellow PHP function, able to generate (compute) a strong random password that respects the aforementioned algorithm (12 lowercased, uppercased, numeric, and special characters).
function generate_password( $length = 12 ) { $password = null; $charset = array('abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '0123456789', '@.#!$%_*~'); $csl = 4; $max_cps = $length >= 12 ? 9 : 9 - 12 + $length; $cps = array(); while (true) { for ($i=0; $i < $csl; $i++) { $cps[$i] = random_int(1, $max_cps); } if (array_sum($cps) == $length) { break; } } foreach ($charset as $key => $val) { for ( $i = 0; $i < $cps[$key]; $i++ ) { $password .= substr( $val, random_int( 0, strlen( $val ) - 1 ), 1 ); } } return str_shuffle($password); }
The function uses four sets of lowercased, uppercased, numeric, and special characters, extracts a random string of a random length from each set until the compute of 12 (the $length) characters. And finally, it shuffles the already randomized result. The only secret here is how it computes the random length of characters to be used from each set.
Use it whenever you want or have to provide users with a strong random password.
For a better security, beside a strong password, a web platform should always provide more security tools, like 2FA (two factor/step auth) - in case of leaked passwords, fail2ban - against brute force login attempts, and passwords stored as hashed and salted with bcrypt, crypt blowfish, argon2 - against rainbow table attacks.
Stay safe.