Sanitary HTML input

I am considering adding a rich text editor so that a non-programmer can change the aspect of the text. However, one of the problems is that you can distort the layout of the displayed page if the layout is incorrect. What is a good easy way to disinfect html?

+8
html php sanitization
source share
4 answers

You will need to decide between good and easy. The recommended choice is HTMLPurifier, as it provides safe defaults. HtmLawed is often recommended as a faster alternative.

See also this fairly objective review from the author of HTMLPurifier: http://htmlpurifier.org/comparison

+14
source share

I really like the HTML Cleaner , which allows you to specify which tags and attirbutes are allowed in your HTML code, and generates valid HTML.

+6
source share

Use BB codes (or like here on SO), otherwise the chances are very thin. Function example ...

function parse($string){ $pattern = array( "/\[url\](.*?)\[\/url\]/", "/\[img\](.*?)\[\/img\]/", "/\[img\=(.*?)\](.*?)\[\/img\]/", "/\[url\=(.*?)\](.*?)\[\/url\]/", "/\[red\](.*?)\[\/red\]/", "/\[b\](.*?)\[\/b\]/", "/\[h(.*?)\](.*?)\[\/h(.*?)\]/", "/\[p\](.*?)\[\/p\]/", "/\[php\](.*?)\[\/php\]/is" ); $replacement = array( '<a href="\\1">\\1</a>', '<img alt="" src="\\1"/>', '<img alt="" class="\\1" src="\\2"/>', '<a rel="nofollow" target="_blank" href="\\1">\\2</a>', '<span style="color:#ff0000;">\\1</span>', '<span style="font-weight:bold;">\\1</span>', '<h\\1>\\2</h\\3>', '<p>\\1</p>', '<pre><code class="php">\\1</code></pre>' ); $string = preg_replace($pattern, $replacement, $string); $string = nl2br($string); return $string; } 

...

 echo parse("[h2]Lorem Ipsum[/h2][p]Dolor sit amet[/p]"); 

Result...

 <h2>Lorem Ipsum</h2><p>Dolor sit amet</p> 

enter image description here

Or just use HTML Purifier :)

+2
source share

Both HTML cleaners and htmLawed are good. htmLawed has the advantage of a much smaller size and high configuration. In addition to performing the standard work of balancing tags, filtering certain HTML tags or their attributes or attribute contents (through white or black lists), etc., It also allows you to use custom functions.

+1
source share

All Articles