5

I am using Rich Text Editor for accepting input data which has HTML content from client side.

On the server side, I am using PHP based server and sanitize the incoming data.

Is there a builtin PHP functionality, which retains the HTML code and removes the presence of Javascript for XSS + SQL injection codes.

Faiz Mohamed Haneef
  • 3,418
  • 4
  • 31
  • 41

3 Answers3

6

As far as I know, there is no existence of such a built in functionality.

The sanitize filters from http://php.net/manual/en/filter.filters.sanitize.php doesn't look to cover your request. You may take a look at http://php.net/manual/en/book.filter.php, but no filter is there set to filter HTML.

I know you don't ask for an external library, but this is the one I think that may help you with the issue you're facing: http://htmlpurifier.org/

Federico J.
  • 15,388
  • 6
  • 32
  • 51
5

Use prepared statements and parameterized queries to prevent SQL injections.

If you want to allow only certain tags to be saved in your database you can use strip_tags(). It gives you the possibility to allow certain HTML tags. However, comments and PHP tags will always be stripped.

$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
Community
  • 1
  • 1
oshell
  • 8,923
  • 1
  • 29
  • 47
3

Regarding the SQL Injection you should use the PDO with prepared statements. This way the string you send to the database is exactly the same as the one you want and you don't need to play with it and escape things.

Regarding the XSS - you should take a look at the XSS Filter Evasion Cheat Sheet by owasp. There are several things you can do here - you can allow only known tags (and strip all the rest, using php's strip_tags function). Note that it will not prevent from XSS inside element's attributes (check the cheat sheet link).
You can use the DOMDocument parser in order to walk through all the elements and check their attributes and keep/remove whatever you want. Check this for more information.

In case you use some known framework most of them have a builtin xss filter, so you can take a use it (or take a look at the code and learn from it).

Community
  • 1
  • 1
Dekel
  • 60,707
  • 10
  • 101
  • 129