Specifications
The PHP function crypt() provides a one-way cryptographic hash function. The prototype for
this function is
string crypt (string str [, string salt])
Given the string str, the function will return a pseudo-random string. For example, given the
string “pass” and the salt “xx”, crypt() returns “xxkT1mYjlikoII”. This string cannot be
decrypted and turned back into “pass” even by its creator, so it might not seem very useful at
first glance. The property that makes crypt() useful is that the output is deterministic. Given
the same string and salt, crypt() will return the same result every time it is run.
Rather than having PHP code like
if( $username == “user” && $password == “pass” )
{
//OK passwords match
}
we can have code like
if( $username == ‘user’ && crypt($password,’xx’) == ‘xxkT1mYjlikoII’ )
{
//OK passwords match
}
We do not need to know what ‘xxkT1mYjlikoII’ looked like before we used crypt() on it.
We only need to know if the password typed in is the same as the one that was originally run
through crypt().
As already mentioned, hard-coding our acceptable usernames and passwords into a script is a
bad idea. We should use a separate file or a database to store them.
If we are using a MySQL database to store our authentication data, we could either use the
PHP function crypt() or the MySQL function PASSWORD(). These functions do not produce
the same output, but are intended to serve the same purpose. Both crypt() and PASSWORD()
take a string and apply a non-reversible hashing algorithm.
To use PASSWORD(), we could rewrite the SQL query in Listing 14.2 as
select count(*) from auth where
name = ‘$name’ and
pass = password(‘$password’)
This query will count the number of rows in the table auth that have a name value equal to the
contents of $name and a pass value equal to the output given by PASSWORD() applied to the con-
tents of $password. Assuming that we force people to have unique usernames, the result of this
query will be either 0 or 1.
Implementing Authentication with PHP and MySQL
C
HAPTER 14
14
IMPLEMENTING
AUTHENTICATION
311
18 7842 CH14 3/6/01 3:35 PM Page 311










