How to create a password generator with PHP

Posted 4 years ago by Matt

Ok, so in this tutorial I'll show you how to write a simple function that will return a random alphanumeric password of the length that you choose. This function could have many uses like generating a unique user ID, automatically generating a new password for users who requested a new password and so on.

We'll start by creating a function that will hold 1 argument: $length, that will represent the length of the generated password:

function generatePassword($length = 8){

We default the length to 8 just so if no arguments are passed it will return a password which is 8 characters long. The next thing we do is start with a blank password and define a variable containing a string of all the possible characters:

$password = null;
$possibleChars = "12346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ";

Next we'll find what the length of our string is and make sure that the passed argument for the length of the password is not bigger than the string, in which case we set the maximum length to the length of our string:

$maxLength = strlen($possibleChars); 
if ($length > $maxLength) {
    $length = $maxLength; 
}

Now we need to create a loop to go through our string of possible characters, pick a random character (that has not been used before) and repeat this for the amount of times defined on the $length variable:

$i = 0;
while ($i < $length) {
    $char = substr($possibleChars, mt_rand(0, $maxLength - 1), 1); 
    if (!strstr($password, $char)) {
        $password .= $char;
        $i++; 
    }
}

To expand on the code above, the line $i = 0; starts a counter which we'll increment by one each time the code goes through the loop and when it's value is equal to the $length variable we stop the loop: while ($i < $length) {

The next line picks a random character from the possible ones followed by condition that checks whether that character was previously used or not, if it was than nothing happen and it runs the loop again, otherwise we add the character to the $password variable and increment the counter by one.

The last thing we need to do is return the password: return $password;

Now in order to use the function you could use something like this:

generatePassword(4); //returns a 4 character long password 
generatePassword(); //returns an 8 character long password

And here's the full code:

function generatePassword($length = 8){
    $password = "";
    $possibleChars = "12346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ";

    $maxlength = strlen($possibleChars);
	  
    if ($length > $maxlength) {
        $length = $maxlength;
    }
		
    $i = 0; 
		
    while ($i < $length) { 
	
        $char = substr($possibleChars, mt_rand(0, $maxlength-1), 1);
			
        if (!strstr($password, $char)) { 
            $password .= $char;
            $i++;
        }
    }
    return $password;
}

Quick links