1

I'm running a MySql and PHP driven blog/comment styled site, and want to make it so users can add formatting tags into their posts, such as a <bold>, <italics>, etc. tags, however, while running something like htmlentities so the user can't post something like <a> or <div id="footer"> and break the site.

So the problem is how do I address this issue? Do I make it so htmlentities or a similar function has a whitelist of allowed tags? I haven't been able to find any results or assistance on this issue. Currently the ordering of layering I have going for the database entity is:

$content = nl2br ($_POST["content"]);
$content = mysql_real_escape_string($content);
$content = trim($content);
$content = htmlentities($content);

Thanks for any help. Again, I'm wondering if htmlentities is even the function I want to utilize to accomplish this, so any suggestions or places to look would be greatly appreciated!

Brandon.B
  • 69
  • 2
  • 10
  • Your order of operations is way, way off. You shouldn't be doing content filtering *at the same time* as your SQL escaping. [Read more](http://stackoverflow.com/a/3126175/168868). – Charles Dec 23 '12 at 09:20
  • Sorry, I'm still very new to DB input sanitation. How should I be doing this? The nl2br was the method I found to make sure the /n linebreaks would keep that formatting in an easy way. – Brandon.B Dec 23 '12 at 10:25
  • Please read the link I posted. The one labeled "read more." It will teach you about the different types of validation and sanitation and where and when they should be used. – Charles Dec 23 '12 at 15:35
  • Thank you - I didn't see that part last night. This was very informative – Brandon.B Dec 23 '12 at 23:53
  • So my understanding is that I would be using the escape_string and trim functions for data that is being inputted into the database, and that you would use htmlentities or strip_tags for html tag filtering and whitelisting when you're retrieving that data to embed into the web page? Again, I'm still new to db sanitizing and validation, so thank you for guidance on this issue. – Brandon.B Dec 24 '12 at 01:01

1 Answers1

2

Whitelist is a MUST... Use strip_tags() function, with second parameter.

// Allow <p> and <a>
echo strip_tags($text, '<p><a>');

Don't save encoded html in database.

Glavić
  • 42,781
  • 13
  • 77
  • 107