Welcome to part 2 of the guestbook tutorial. So, in part one, you learned how to add messages to the guestbook, and how to display them on the web page. Good stuff. In this part you’re going to learn how to create a password protected login area to delete those nasty spam attacks and perform other censorship!
Remember in part one we created a table in your database to hold the username and password of the administrator? Well, first things first that wants populating. For the sake of simplicity I’m only going to show you how to add a single username/ password, but you can have as many as you want!
Ok, so my example username will be TonyBlair and the password will be LiedToMe, as these are not only memorable examples, but also true. Here’s how we’re going to get this information into the database:
<?php
//connect to db
$cxn=mysql_connect(“localhost”,”username”,”password”);
if(!$cxn){
die(“Database connection failed: “.mysql_error());
}
$dbcxn=mysql_select_db(database_name,$cxn);
if(!$dbcxn){
die(“Database selection failed: “.mysql_error());// add details to login table
$username=”TonyBlair”;
$password=”LiedToMe”;
$password=md5($password);
mysql_query(“INSERT INTO login
(username, password) VALUES($username, $password) “)
or die(mysql_error());
echo”Login created”;
?>
So you’ll hopefully have noticed the md5() function in there? If you don’t know what that is, it’s an encryption that php applies to the password to make it secure. If anyone hacks your database, in the password field they will simply see a long string of random looking characters. As a rule of thumb, md5 can only be processed one way, making it (nearly) impossible to decypher.
//log me in
Now we need a page with a form so that our administrator can log in. This is just a simple HTML job:
<div id=”login”>
<form method=”post” action=”checklogin.php”>
<fieldset>
<legend>Admin area Login</legend>
<ul>
<li><label for=”username”>Username</label>
<input type=”text” name=”username”></li>
<li><label for=”password”>Password</label>
<input type=”password” name=”password”></li>
<li><label for=”submit”></label>
<input type=”submit” value=”login”></li>
</ul>
</fieldset>
</form>
</div>
Save this as login.php or even login.html. Both will work here, but for the rest of this tutorial I’m going to use the .php extension regardless of whether it’s necessary. You’ll have noticed here, and in part one, that I’ve used super accessible HTML for this form, none of your table based nonsense here sunshine! This code is a CSS magnet!
I digress… Ok, the login form is processed by a script called checklogin.php which looks like this:
<?php
include(“connect.php”);//get username and password from form
$username=$_POST['username'];
$password=$_POST['password'];//protect db from sql injection
$username=stripslashes($username);
$password=stripslashes($password);
$username=mysql_real_escape_string($username);
$password=mysql_real_escape_string($password);
$password=md5($password);
//get data from database
$sql=”SELECT * FROM logins WHERE username=’$username’ and password=’$password’”;
$result=mysql_query($sql);
//mysql num row is counting table row
$count=mysql_num_rows($result);
//if results match, then $count=1
if($count==1){
//register username and password, redirect to login_success.php
session_register(“username”);
session_register(“password”);
header(“location:login_success.php”);
}
else{
echo ‘<a href=”login.php”>Access Denied. You have brought shame on your family, click here to go back</a>’;
}
?>
Hopefully you’ll have enough knowledge from part one to see how most of this works. First the script connects to the database using the code in connect.php, then it assigns the data sent by the form in login.php to the variables $username and $password. This data is then protected against ‘terrorism’ using stripslashes and mysql_real_escape_string, and finally the password is encrypted using md5. Got that? Good. Next, the script queries the database, and looks for a match for the username and password in the same row. This is potentially very important in a database with loads of users, as some may have the same usernames or passwords. This way, the query only returns TRUE if the username and password match in a single row. This little nugget does the business: $count=mysql_num_rows($result);
If $count returns a 1 (true) then the next bit of code is processed. At this point, php creates a session which allows us to check whether a user is logged in as they progress though the admin area. The user is redirected to login_success.php. If $count returns false (0) the user is told to go back and try again, tail between legs.
//administer my guestbook
Keeping up? Excellent. Here’s a peek at login_success.php
<?php
//check if session is registered, if not then redirect back to main page
session_start();
if(!session_is_registered(username)){
header(“location:login.php”);
}include(“connect.php”);//collect all guestbook data from database
$query=”SELECT * FROM guestbook”;
$result=mysql_query($query)or die(mysql_error());
//run the while loop that displays all the comments
while ($row=mysql_fetch_array($result))
{
//grab the ID of the message for use in the link to delete messages from db
$id=$row['ID'];
//display the comment and the users email address
echo ‘<div class=”message”><p class=”name”>’.$row['name'].’ | ’;
echo ‘<a href=”mailto:’.$row['email'].’”>’.$row['email'].’</a></p>’;
echo ‘<p>’.$row['message'].’</p>’;
//create a button to delete the comment
echo ‘<form class=”delete” method=”post” action=”delete.php”><input type=”hidden” name=”name” value=”‘.$id.’”/><input type=”submit” value=”Delete this comment”/></form>’;
echo ‘</div>’;
}
?>
<a href=”logout.php”>logout</a>
Ok, there’s two bits there you may not recognise, but hopefully by now the rest will be like sleaze to a politician. So the first bit checks to see if you are logged in using the session_start() function. It’s black and white really, if you’re not logged in, you get kicked back to login.php. If you are logged in, the rest of the script will be processed. The delete button is created via a wee form at the bottom, which to the user just looks like a button. The form is processed by delete.php, and catches the id of the row to be deleted from the database using $_POST. This value is hidden from the user and POSTed along with the highly creative and descriptive name of ‘name’ when the button is clicked. Here’s how it works:
<?php
//check if session is not registered then redirect back to main page
session_start();
if(!session_is_registered(username)){
header(“location:main_login.php”);
}//connect to db
include(“connect.php”);//delete the entry
if(isset($_POST['name']))
{
$id=$_POST['name'];
$sql=”DELETE FROM guestbook WHERE id=$id”;
$result=mysql_query($sql)or die(mysql_error());
echo ‘<p>Comment deleted</p>’;
}
echo ‘<p><a href=”login_success.php”>Click here to go back</a></p>’;
?>
I hope this is fairly self explanatory. The script checks that you are logged in, then assigns the $id var with the ‘name’ or ID of the row to be deleted. Then it deletes it! Simple.
//log me out!
And that’s almost it, folks, but if you’ve been paying attention (and I know you have), you’ll have noticed that the very last line of login_success.php is a link to log out of the admin area. This is the simplest part of all. Predictably, the highly creative nodes in my brain have called this script logout.php.
<?
session_start();
session_destroy();
?><p>You have logged out successfully.</p>
<p><a href=”guestbook.php”>Click here to continue</a></p>
Could it be any easier? Probably, but that’s how I’ve done it. The session is deleted or destroyed, and the user is guided back to the guestbook page.
Well, that’s your lot.com! I hope you have enjoyed this tutorial, and I very much look forward to the interweb being populated by clones of this superior guestbook script. If you have any comments or criticisms, please feel free to voice them in the comments section below. And before you go, pay my good friend ElanMan a visit too. He’s got some great code snippets if you’re still hungry for more.
Ciao!

Nice tutorial there !b, well done sir!
I look forward to reading more of your stuff