Checking Usernames and Passwords

When validating a username and a password (for example, in a script that backs an HTML login form), two things seem to form a de facto standard on the Web:

  • The password is always case sensitive. It has to be provided exactly the same way it was set.

  • The username, however, is not case sensitive.

Therefore, a username has to be compared without considering case sensitivity. This can be done either by using strcasecmp()see the previous tutorial or by first converting both the provided password and the real password into lowercase letters (or uppercase letters). This is done by the functions strtolower() or strtoupper(). The preceding code shows an example, using strcmp()/strcasecmp() and also the compare operator ===.

Validating Logins by Comparing Strings

  $user = (isset($_GET['user'])) ? $_GET['user'] : '';
  $pass = (isset($_GET['pass'])) ? $_GET['pass'] : '';
  if (
    (strtolower($user) === 'damon' && $pass === 'secret') ||
    (strtoupper($user) === 'SHELLEY' && $pass === 'verysecret') ||
    (strcasecmp($user, 'Christian') == 0 && strcmp($pass, 'topsecret') == 0)
  ) {
    echo 'Login successful.';
  } else {
    echo 'Login failed.';

Depending on the data provided in the uniform resource locator (URL) of the call to the script, the login either fails or succeeds. For instance, the following URL successfully logs in the user (you have to change the servername portion):


On the other hand, the following login does fail:


Of course, providing usernames and passwords via GET is a very bad idea; POST is preferred (see Tutorial 4, "Interacting with Web Forms," for more details on form data). However, for testing purposes, this chapter's code uses GET.

by BrainBellupdated