Webmaster often needs to generate random password for new users. There are many way to do this but I found a very simple method which can generate strong password of any length. This method is based on str_shuffle() function which randomly shuffles a string.
<? function generate_password( $length = 8 ) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?"; $password = substr( str_shuffle( $chars ), 0, $length ); return $password; } ?>
To generate random password simply pass the desired length of password in this function. If you omit length parameter then it will generate 8 character long password by default.
$password1 = generate_password(); // default length 8 $password2 = generate_password(6); // 6 character long password
Great !!
We can improve by adding the choice of the complexity of the password with this little trick.
function generate_password($length = 8, $complex=3) {
$min = "abcdefghijklmnopqrstuvwxyz";
$num = "0123456789";
$maj = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$symb = "!@#$%^&*()_-=+;:,.?";
$chars = $min;
if ($complex >= 2) { $chars .= $num; }
if ($complex >= 3) { $chars .= $maj; }
if ($complex >= 4) { $chars .= $symb; }
$password = substr( str_shuffle( $chars ), 0, $length );
return $password;
}
echo generate_password(8);
or just
return substr(str_shuffle(“abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?”), 0, $length);
best and shorter way. Thanks for sharing