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 mysqli_connect() and mysqli_real_escape_string() lines, like this:

$GuestName = str_ireplace("dog", "***", $_POST['GuestName']);
$GuestEmail = str_ireplace("dog", "***", $_POST['GuestEmail']);
$GuestMessage = str_ireplace("dog", "***", $_POST['GuestMessage']);
$GuestName = mysqli_real_escape_string($db, $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:

$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 = mysqli_real_escape_string($db, $GuestName);
$GuestEmail = mysqli_real_escape_string($db, $GuestEmail);
$GuestMessage = mysqli_real_escape_string($db, $GuestMessage);
$CurrentTime = time();


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Building a better guestbook >>

Previous chapter: Problems in paradise: Guestbook v2

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.