User Log-in

Now we need another form, one which will take the user's information and match it up in the database. This is another HTML page:

<title>User Registration</title>

<form action="login.php" method="post">
Username: <input type="text" name="username" size="20"><br>
Password: <input type="password" name="password" size="20"><br>
<input type="submit" value="Log In">


Call the file login.html. Now for login.php, which is the actual script:



// connect to the mysql server
$link = mysql_connect($server, $db_user, $db_pass)
or die ("Could not connect to mysql because ".mysql_error());

// select the database
or die ("Could not select database because ".mysql_error());

$match = "select id from $table where username = '".$_POST['username']."'
and password = '".$_POST['password']."';"; 

$qry = mysql_query($match)
or die ("Could not match data because ".mysql_error());
$num_rows = mysql_num_rows($qry); 

if ($num_rows <= 0) { 
echo "Sorry, there is no username $username with the specified password.
"; echo "Try again"; exit; } else { setcookie("loggedin", "TRUE", time()+(3600 * 24)); setcookie("mysite_username", "$username"); echo "You are now logged in!
"; echo "Continue to the members section."; } ?>

Scared yet? Well don't be, it's a lot simpler than it looks! It should all look familiar up to the line $match = "select id.... This line, when called by mysql_query, searches the table for the username and password entered. mysql_num_rows is the number of rows that the search found, and should be 1, as all username are unique.

If no row (or user, with a matching password,) is found, an error message is printed, along with a link to try again. Otherwise, a cookie called "loggedin" is set, which will allow the user access to the members area for one day. A success message is then printed along with a link to the members area.

Now you're almost done, except for the cookie check function in the members area. Place the following snippet of PHP code at the top of all pages in the members area:

<?php if (!isset($_COOKIE['loggedin'])) die("You are not logged in!"); ?>

If the cookie "loggedin" is set (which is done by login.php) then the page will be displayed. If it is not set, it will display "You are not logged in!" instead.

If you wish to display a "you are logged in as username" message, include this in your members page(s):

$mysite_username = $HTTP_COOKIE_VARS["mysite_username"]; 
echo "you are logged in as $mysite_username";

Now that they're logged in, we need to provide a way to log out when they're done.