PHP

Authenticating a user against an encrypted password in the users table

<?php
include 'db.inc';
function authenticateUser($connection,
                          $username,
                          $password)
{
  // Test the username and password parameters
  if (!isset($username) || !isset($password))
    return false;
  // Get the two character salt from the
  // username collected from the challenge
  $salt = substr($username, 0, 2);
  // Encrypt the password collected from
  // the challenge
  $crypted_password = crypt($password, $salt);
  // Formulate the SQL find the user
  $query = "SELECT password FROM users
               WHERE user_name = '$username'
               AND password = '$crypted_password'";
  // Execute the query
  $result = @ mysql_query ($query,
                           $connection)
  or showerror(  );
  // exactly one row? then we have found the user
  if (mysql_num_rows($result) != 1)
    return false;
  else
    return true;
}
?>

The authenticateUser( ) function developed in Example 9-7 is likely to be used in many scripts and writing the code to a authentication.inc file allows the function to be included in the scripts that require authentication. We could rewrite Example 9-4 to use the database authentication function by including the authentication.inc file:

<?php
include("authentication.inc");
include("db.inc");
include("error.inc");
// Connect to the MySQL server
// Connect to the Server
if (!($connection = mysql_connect($hostName,
                    $username, $password)))
    die("Could not connect to database");
if (!mysql_selectdb("$databaseName, $connection)
   showerror();
if !authenticateUser($connection,
                     $PHP_AUTH_USER,
                     $PHP_AUTH_PW)))
{
  // No credentials found - send an unauthorized
  // challenge response ...
  header("WWW-Authenticate: Basic realm=\"Flat Foot\"");
  header("HTTP/1.0 401 Unauthorized");
  // ...
  exit;
}
// The HTML response to authorized users ...
?>

MySQL encryption

MySQL provides the encryption function password( ) that can be used instead of the crypt( ) function; we introduced this function in Chapter 3. The MySQL password( ) function can be incorporated into the SQL update or insert queries:

$update_query =
  "UPDATE users
     SET password = password($password)
     WHERE user_name = '$username'";

Like crypt( ), the MySQL password( ) function is a one-way function, but it is simpler to use because it doesn't require a salt string. However, when identical passwords are used, they are stored as identical encrypted strings. Another disadvantage to using the MySQL password( ) function is that the password is transmitted between the web server and the MySQL DBMS in its unencrypted form. We recommend that crypt( ) be used rather than the MySQL password( ) function when building web database applications.