Skip to content Skip to sidebar Skip to footer

Sanitize Html5 With Php (prevent Xss)

I'm building WYSIWYG editor with HTML5 and Javascript. I'll allow users post pure HTML via WYSIWYG, so it have to be sanitized. Basic task like protecting site from cross site scri

Solution 1:

PHP offers parsing methods to protect from code PHP/SQL injections (i.e. mysql_real_escape_string()). This is not the case for HTML/CSS/JavaScript. Why that?

First: HTML/CSS/Javascript sole purpose is to display information. It is pretty much up to you to accept certain elements of HTML or reject them depending of your requirements.

Secondly: due to the very high number of HTML/CSS/JS elements (also increasing constantly), it is impossible to try to control HTML. you cannot expect a functional solution.

This is why I would suggest a top-down solution. I suggest to start restricting everything and then only allowing a certain number of tags. One good base is probably to use BBCdode, pretty popular. If you want to "unlock" additional specific tags beyond BBCode, you can always add some.

This is the reason BBCode-like scripts are popular on forums and websites (including stack overflow). WISIGIG editors are designed for admin/internal use, because you don't expect your website administrator to inject bad content.

bottom-top approaches are vowed to fail. HTML sanitizers are exposed to exponential complexity and do not guarantee anything.


EDIT 1


You say it is a sanitation problem, not a front end issue. I disagree, because as you cannot handle all present and future HTML entities you would better restrict it at a front end level to be 100% sure.

This said, perhaps the below is a working solution for you:

  1. you can do a bit to sanitize your code by striping all entities except those in a white list using PHP's strip_tags().
  2. You can also remove all remaining tags attributes (properties) by using PHP's preg_replace() with some regular expression.

$string = "put some very dirty HTML here.";
$string = strip_tags($string, '<p><a><span><h1><li><ul><br>');
$string = preg_replace("/<([b-z][b-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>', $string);
echo$string;

This will return your sanitized text.

note : I have excluded attributes removal for tags because you may still want to keep href="" properties. hence the [b-z][B-Z] regex.

Solution 2:

I Believe the ideal is to use a combination :

  mysql_real_escape_string(addslashes($_REQUEST['data']));

On Write

and

stripslashes($data) 

on read always did the trick for me, I think it is better than

  htmentities($data) on write

and

  html_entity_decode($data) on read

Post a Comment for "Sanitize Html5 With Php (prevent Xss)"