Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape all HTML except <br>

I am trying to display comments on a page and am having some trouble.

There are essentially two different types of comments I am trying to handle:

(1) The XSS type.. e.g. <script type="text/javascript">alert('hi')</script>. This is handled fairly easily by escaping it before it gets into the database and then running stripslashes and htmlentities on it.

(2) The comment with <br> breaks in it. When the data is stored into the database, I am running nl2br on it so the data looks like hi<br>hello<br><br>etc. However, when I display this comment, the <br>s do not turn into page breaks like I want them to.

Any idea what to do? I should note that turning off htmlentities fixes the second type, but the first type then is executed as pure html and displays an alert dialog.

Thanks, Phil

like image 997
psarid Avatar asked May 13 '11 03:05

psarid


2 Answers

If you want to remove unwanted tags you can try strip_tags. It supports allowable_tags so you can specify any tags that you don't want to be stripped. A sample from the manual:

// Allow <p> and <a>
// you can add <br> if you want it not stripped
echo strip_tags($text, '<p><a>');

So after you've converted all \n to be line breaks you dont have to worry about it being stripped. May not be what you want but hope it gives an idea.

like image 200
tradyblix Avatar answered Oct 14 '22 19:10

tradyblix


One method: Replace <br> with a placeholder, like \n. Then do htmlentities to clean up html code. Finally, replace \n back with <br> to recover the line breaks.

like image 28
mellamokb Avatar answered Oct 14 '22 19:10

mellamokb