Password Generator Written In PHP

Watch out! This tutorial is over 2 years old. Please keep this in mind as some code snippets provided may no longer work or need modification to work on current systems.
Tutorial Difficulty Level    

To mark #WorldPasswordDay, today we will look at how to generate a strong password inside your PHP application.

We’ll create a function called generatePassword() that will take four arguments, each optional: The length of the password, plus the number of capitals, numbers and symbols it should have.

If no parameters are given, the function will return 8 random lower-case letters. The function will also test its attributes to see if too many capitals, numbers or symbols are requested; if so, the function will return Boolean false and raise a PHP warning error.

Note that while no password based on mt_rand() and shuffle() is truly “random” these should suffice for all intents and purposes.

Line 3 is going to tell us if we need any caps, numerals or symbols in our password. It’s also going to tell us if the total number of non-lower-case letters is greater than the requested password length.

Lines 6-29 test the inputs to ensure we have values of the right type and in range; that no one non-lower-case-letter request is greater than the requested password length; and that the total of all requested “special” characters does not exceed the requested password length. If any of those conditions are not met, the function raises a PHP warning and returns false.

Lines 34-37 provide the seed characters that can appear in a returned password. You can edit these strings as you like, if you want to add or remove characters (e.g., some people will want to not pass the letter “o” if the numeral “0” can also be returned).

Lines 40-42 create a base password of all lower-case letters. It does so by using mt_rand() to pick a number between 0 and however long the base $chars string is; then, grabbing a single letter, at whatever index of the $chars string is chosen by mt_rand(); using substr() to grab that single character; then appending that character to the string we will output ($out).

If there’s no request for capitals, numbers or symbols in our password, we’re done. But if we do need “special” characters (which is determined at Line 45, by determining if $count is greater than 0), then:

Lines 47-48 prepare two arrays: One that converts our base password into a character array, and another that preps a second array to which we will add our “special” characters.

Lines 51-59 append the required special characters onto our second array.

Note that the benefit of the PHP for() control structure is that we can bypass its execution by conditioning its execution on an evaluation that is initially false. In other words, I can add a for() loop to my code, but it will not execute so long as its second argument — the one that evaluates whether the control should execute — is false.

Line 62 lops a chunk off the front of our original password array, using array_slice(), that’s as big as the number of “special” password characters we requested. This is so we can merge those special characters into that array, using the aptly named array_merge() function, which is done at Line 64.

You might be asking yourself, “Why not use array_splice() here? It’s supposed to do exactly what you did with those two functions.” The answer is, I tried that, but I couldn’t get it to work properly; so, a bit more verbose a solution to achieve the same end. It’s inelegant and I know it; if you have alternative code that works better, please comment and I will incorporate it here.

Line 66 calls the handy shuffle() function, which mixes up the characters in an array; Line 68 converts the password back into a string for output. Line 71 returns the password if there wasn’t an error.


To use this generator, you just need to add its code somewhere on the page where it will be used, and then call it as you would any built-in PHP function:

It’s worth noting that some characters have special meanings in PHP and MySQL, notably the parentheses, dollar sign and arithmetic operators. For example, this password generator could produce double-minus signs, which is the comment character in MySQL; if you got double-dashed in a password and didn’t escape them before using the password in a SQL comment, it could cause SQL errors. The easiest thing to do is remove, from the symbols string at Line 49, any characters that might cause troubles for your code.

Also, if you are going to use this with a form, as in the demo code, it’s worth noting that all POST and GET variables are passed as strings. Therefore, you must explicitly cast your form variables as integers when passing them to your function.