Anyone who has ever dealt with user authentication knows how important a strong password is, this is a very simple, and small function that will generate a password of variable length and complexity. The function accepts two options; the first, length is self explanatory. This is the length of the password you wish to generate, a common length is 6-8. The second is the complexity of the password, this involves the possible characters from which the password will be generated. I designed this to accept values 1-4 (any other value will default to 4) where 1 is the weakest and 4 the strongest.
The function returns a generated password.
function generate_password ( $length = 8, $complexity = 3 )
{
$password = '';
switch ( $complexity )
{
case 1:
$possible = '0123456789';
break;
case 2:
$possible = '0123456789bcdfghjkmnpqrstvwxyz';
break;
case 3:
$possible = '0123456789bcdfghjkmnpqrstvwxyzABCDEFGHIJKLMOPQRSTUVWXYZ';
break;
case 4:
default:
$possible = '0123456789bcdfghjkmnpqrstvwxyzABCDEFGHIJKLMOPQRSTUVWXYZ@#$%&!?^~';
break;
}
$i = 0;
while ( $i < $length )
{
// pick a random character from the possible ones
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
// we don't want this character if it's already in the password
if ( !strstr($password, $char) )
{
$password .= $char;
$i++;
}
}
return $password;
}