3

I am looking for a way or function that will allow me to display data from my mySQL database. The users are allowed to post articles, that I use mysql_real_escape_string to avoid SQL injections before inserting their post in the DB.

For my testing pursposes I write in a text area my post with tags like <b> <a> <i> <li>. Later I will use an editor like this one here on Stackoverflow to help users with their posts.

However, I am aware of XSS and just echoing straight from the DB may lead to XSS attacks. So, I choosed for my tests to output the content with htmlentities or htmlspecialchars. None of them will show me the post correctly with html.

Therefore, I used strip tags but as far as I know and read, is not safe.

What is a function that you may use too, that will let me output the data correctly, just like this and prevent XSS?

EnexoOnoma
  • 8,454
  • 18
  • 94
  • 179
  • 2
    Use [HTMLPurifier](http://htmlpurifier.org/). It'll be as harsh as you want with the given html and ruthlessly (or politely) rip out anything you don't want in there. – Marc B Aug 26 '11 at 22:08
  • @Marc B : Is HTMLPurifier light? – EnexoOnoma Aug 26 '11 at 22:30

1 Answers1

0

If you want to display html correctly you should print plain html as you get it. But for avoiding XSS try to remove javascript tags and don't allow load images from external resources.

Andrej
  • 7,474
  • 1
  • 19
  • 21
  • How can I entirely remove javascript tags? What is the logic to avoid external images? – EnexoOnoma Aug 26 '11 at 22:00
  • Good answer for removing javascript: http://stackoverflow.com/questions/1886740/php-remove-javascript – Andrej Aug 26 '11 at 22:02
  • Don't allow users to add link to images from external resources except yours. – Andrej Aug 26 '11 at 22:03
  • Because of instead image you will load dangerous code from external site. – Andrej Aug 26 '11 at 22:20
  • removing script tags is not enough. Here is a simple example: – Erlend Aug 27 '11 at 07:41
  • in some recent versions of browsers it was possible to load svg images with javascript through tags. However I think that has been disabled. The images will load, but the scripts will not run. – Erlend Aug 27 '11 at 07:45
  • This is a good article, by Chris Shiflett http://shiflett.org/blog/2007/mar/allowing-html-and-preventing-xss about allowing basic HTML while avoiding XSS with php for blog comments. – Marcel Jan 04 '13 at 13:22