22.2.4 Fixing the problemsThis is NOT the latest copy of this book; click here for the latest version.
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 "<B>Posted by <A HREF=\"mailto:$gb_GuestEmail\"> $gb_GuestName</A> on $gb_DateSubmitted</B><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();
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|