14.5. Checking Password Strength

Problem

You want to make sure users pick passwords that are hard to guess.

Solution

Test a user’s password choice with the pc_passwordcheck( ) function, shown later in Example 14-1. For example:

if ($err = pc_passwordcheck($_REQUEST['username'],$_REQUEST['password'])) {
    print "Bad password: $err";
    // Make the user pick another password
}

Discussion

The pc_passwordcheck( ) function, shown in Example 14-1, performs some tests on user-entered passwords to make sure they are harder to crack. It returns a string describing the problem if the password doesn’t meet its criteria. The password must be at least six characters long and must have a mix of uppercase letters, lowercase letters, numerals, and special characters. The password can’t contain the username either in regular order or reverse order. Additionally, the password can’t contain a dictionary word. The filename for the word list used for dictionary checking is stored in $word_file.

The checks for the username or dictionary words in the password are also applied to a version of the password with letters substituted for lookalike numbers. For example, if the supplied password is w0rd$%, the function also checks the string word$% for the username and dictionary words. The “0” character is turned into an “o.” Also, “5” is turned into “s,” “3” into “e,” and both “1” and “!” into “l” (el).

Example 14-1. pc_passwordcheck( )

function pc_passwordcheck($user,$pass) { $word_file = '/usr/share/dict/words'; ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.