generate random password in PHP

Just thought I’d share this little script for generating a random password with PHP. You can customise the length and strength of the password when calling the method.

<?php
function generatePassword($length, $strength) {
$vowels = 'aeiouy';
$consonants = 'bcdfghjklmnpqrstvwxz';
if ($strength == 1) {
$consonants .= 'BCDFGHJKLMNPQRSTVWXZ';
}
if ($strength == 2) {
$vowels .= "AEIOUY";
}
if ($strength == 4) {
$consonants .= '123456789';
}
if ($strength == 8 ) {
$consonants .= '@#$%';
}
$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;
}
?>

you then simply call the function from within your script as:

<?php
$newPass = generatePassword(length, strength);
?>

And there you have it, a randomly generated password. You can play with the strength factros and variables if you wish; entirely up to you.

Advertisements

About Cameron
I'm a final year Computer Science/Information Systems major. Already finished my BA in Politics/Philosophy. I do web and software freelance on the side, while I finish studying. Hoping to be self-employed by the end of my degree, otherwise off into the real-world I go....

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: