Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if HTML contains JavaScript in PHP

I need to check if user submitted HTML contains any JavaScript. I'm using PHP for validation.

like image 919
David Avatar asked Oct 01 '09 10:10

David


3 Answers

If you want to protect yourself against Cross-Site Scripting (XSS), then you should better use a whitelist than a blacklist. Because there are too many aspects you need to consider when looking for XSS attacks.

Just make a list of all HTML tags and attributes you want to allow and remove/escape all other tags/attributes. And for those attributes that can be used for XSS attacks, validate the values to only allow harmless values.

like image 169
Gumbo Avatar answered Oct 21 '22 02:10

Gumbo


It might be better to take a different approach and use something like HTML Purifier to filter out anything that you don't want. I think it would be very difficult to safely remove any possibility of javascript without actually parsing the HTML properly.

like image 31
Tom Haigh Avatar answered Oct 21 '22 02:10

Tom Haigh


OK, let's not all be naive here:

<script> "<!-- </script> -->"; document.write("hello world"); </script> (should pass the filters suggested by regexadvice)

filtering-out javascript is a security-critical thing, which means you need to do it thoroughly and properly, not some quick hack.

like image 2
OJW Avatar answered Oct 21 '22 01:10

OJW