Specifications
The script’s activities revolve around the $valid_user session variable. The basic idea is that if
someone logs in successfully, we will register a session variable called $valid_user that con-
tains her userid.
The first thing we do in the script is call session_start(). This will load in the session vari-
able $valid_user if it has been registered.
In the first pass through the script, none of the if conditions will apply and the user will fall
through to the end of the script, where we tell her that she is not logged in and provide her
with a form to do so:
echo “<form method=post action=\”authmain.php\”>”;
echo “<table>”;
echo “<tr><td>Userid:</td>”;
echo “<td><input type=text name=userid></td></tr>”;
echo “<tr><td>Password:</td>”;
echo “<td><input type=password name=password></td></tr>”;
echo “<tr><td colspan=2 align=center>”;
echo “<input type=submit value=\”Log in\”></td></tr>”;
echo “</table></form>”;
When she presses the submit button on the form, this script is reinvoked and we start again
from the top. This time, we will have a userid and password to authenticate, stored as $userid
and $password. If these variables are set, we go into the authentication block:
if ($userid && $password)
{
// if the user has just tried to log in
$db_conn = mysql_connect(“localhost”, “webauth”, “webauth”);
mysql_select_db(“auth”, $db_conn);
$query = “select * from auth “
.”where name=’$userid’ “
.” and pass=password(‘$password’)”;
$result = mysql_query($query, $db_conn);
We connect to a MySQL database and check the userid and password. If these are a matching
pair in the database, we register the variable $valid_user that contains the userid for this par-
ticular user, so we know who is logged in further down the track.
if (mysql_num_rows($result) >0 )
{
// if they are in the database register the user id
$valid_user = $userid;
session_register(“valid_user”);
}
}
Advanced PHP Techniques
P
ART IV
442
25 7842 CH20 3/6/01 3:42 PM Page 442










