PDA

View Full Version : Comment Filtering


absolethe
January 22nd, 2005, 00:33
I have written a very simple comment script for my site using PHP and MySQL. I think I'm ready to improve the script by doing the following.

1. Filter out HTML or PHP, except:
2. Allow <strong>, <em>, and <p>.
3. Make sure those tags are appropriately closed.

I read the PHP manual on the strip_tags function and ended up confused by all the different comments. I was wondering if anyone knew of a) a good, readable example or b) a detailed tutorial.

sonicgroup
January 22nd, 2005, 01:33
I've never used the function before, but if what I'm reading is correct, something like this should do the trick:

[syntax:bbf24be276="php"]
$str = 'blah'; // your string to strip tags
$tags = '<strong><em><p>'; // your allowed tags - the description doesn't specify a delimiter, so I'm assuming none
$str = strip_tags($str, $tags); // strip everything but the allowed tags in $tags
[/syntax:bbf24be276]

vigo
January 22nd, 2005, 10:37
Yep, striptags will do the filtering. I think there's a module in PEAR (http://pear.php.net) to correct HTML mis-nesting.

absolethe
January 23rd, 2005, 20:24
Ok...so considering what I've got going on here is...
[syntax:cdbed20fa1="php"]
<?php
/* Find out if a comment has been posted and if so, insert it in the database and refresh the page */
if (isset($_POST['com_submit'])):
$com_date = date("YmdHis");
$com_name = $_POST['com_name'];
$com_email = $_POST['com_email'];
$com_site = $_POST['com_site'];
$comments = $_POST['comments'];
$item_ref = $_POST['item_ref'];
$bl_title = $_POST['bl_title'];
$table = $_POST['table'];

$sql = "INSERT INTO $table (com_id,com_date,com_name,com_email,com_site,comme nts,item_ref) VALUES ('','$com_date','$com_name','$com_email','$com_sit e','$comments','$item_ref')";
$result = mysql_query($sql) or die(mysql_error());
endif;

?>
[/syntax:cdbed20fa1]

I'd just... change it to?
[syntax:cdbed20fa1="php"]
$tags = '<strong><em><p>'; //at the top-ish
$comments = strip_tags($_POST['comments'], $tags); //change to
[/syntax:cdbed20fa1]

I would almost rather use preg_replace, based on all the comments I saw in the PHP Manual. But I suck at regular expressions, they are gibberish to me.

And what about closing tags? And also what about replacing an "enter" with <br/> ?

sonicgroup
January 23rd, 2005, 20:56
Yep, that would do it. As for closing tags, the function removes both starting and ending tags.

To replace linebreaks with <br />, use the nl2br() function when you display the comments (not when they are added).

absolethe
January 23rd, 2005, 21:23
Oooh...this wouldn't be hard to change, then. Lucky me!