Fixing the problems

The SQL for our guestbook remains the same, as does the finished display - all the changes we're going to make will be done internally in the PHP code, and will be invisible to users as long as they do not use filtered words.

To handle filtering, I am going to strip "dog" out at submission time, then "hamster" out at display time - this probably is not ideal for your application, but I have chosen this way to demonstrate how both methods work. In your own code, pick one or the other!

You'll need to open up post.php and add three lines in between the mysql_select_db() and addslashes() lines, like this:

mysql_select_db("phpdb");
$GuestName = str_ireplace("dog", "***", $_POST['GuestName']);
$GuestEmail = str_ireplace("dog", "***", $_POST['GuestEmail']);
$GuestMessage = str_ireplace("dog", "***", $_POST['GuestMessage']);
$GuestName = addslashes($GuestName);

Similarly you will need to edit read.php so that the while loop looks like this:

extract($row, EXTR_PREFIX_ALL, 'gb');
$gb_DateSubmitted = date("jS of F Y", $gb_DateSubmitted);
$gb_GuestName = str_ireplace("hamster", "***", $gb_GuestName);
$gb_GuestEmail = str_ireplace("hamster", "***", $gb_GuestEmail);
$gb_GuestMessage = str_ireplace("hamster", "***", $gb_GuestMessage);
echo
"<strong>Posted by <a href=\"mailto:$gb_GuestEmail\"> $gb_GuestName</a> on $gb_DateSubmitted</strong><br />";
echo
"$gb_GuestMessage<br /><br />";

As you can see, basic filtering is simply a matter of using the case-insensitive string replace function str_ireplace(). You can of course go for more complicated filtering by using regular expressions, but this is usually overkill!

Using the same method it is pretty simple to drop in strip_tags() as necessary to stop people from hijacking your site with unruly HTML or scripting, making post.php look like this:

mysql_select_db("phpdb");
$GuestName = str_ireplace("dog", "***", $_POST['GuestName']);
$GuestEmail = str_ireplace("dog", "***", $_POST['GuestEmail']);
$GuestMessage = str_ireplace("dog", "***", $_POST['GuestMessage']);
$GuestName = strip_tags($GuestName);
$GuestEmail = strip_tags($GuestEmail);
$GuestMessage = strip_tags($GuestMessage);
$GuestName = addslashes($GuestName);
$GuestEmail = addslashes($GuestEmail);
$GuestMessage = addslashes($GuestMessage);
$CurrentTime = time();

 

Next chapter: Building a better guestbook >>

Previous chapter: Problems in paradise: Guestbook v2

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar