tags:

views:

122

answers:

5

Can this code help to sanitize malicious code in user submit form?

function rex($string) {
$patterns = array();
$patterns[0] = '/=/i';
$patterns[1] = '/javascript:/i';
$replacements = array();
$replacements[0] = '';
$replacements[1] = '';
return preg_replace($patterns, $replacements, $string);

I have included htmlentities() to prevent XSS on client side, is all the code shown is safe enough to prevent attack?

A: 

htmlentities alone will do the trick. No need to replace anything at all.

Matchu
+2  A: 

You don't need that if you are using htmlentities. To prevent XSS you can even just use htmlspecialchars.

Just make sure that you use htmlspecialchars on all data that is printed as plain text in your HTML response.

See also: the answers to "Does this set of regular expressions FULLY protect against cross site scripting?"

Daniel Trebbien
+2  A: 

your substitutions may help. But you're better off using a pre-rolled solution like PHP's data filters. Then you can easily limit datatype to what you expect.

dnagirl
Thank, it is very useful!
proyb2
A: 

No. http://ha.ckers.org/xss.html

Arkh
This terse answer is not very helpful without explaining that the http://ha.ckers.org/xss.html page exists to convince developers of the difficulty of making a completely safe filtering scheme for preventing XSS.
Daniel Trebbien
A: 

Your first replacement rule is useless as it can be easily circumvented by using eval and character encoding (and an equal sign isn't necessary for XSS attacks anyway).

Your second rule can be very likely circumvented on at least some browsers by using things like javascript : or java\script:.

In short, it doesn't help much. If you want to show plain text, htmlentities is probably fine (there are exotic attacks which take advantage of unusual character encodings and browser stupidity to launch XSS attacks without any special characters, but that only works on specific browsers - cough IE cough - in specific situations). If you want to put user input in URLs or other attributes, it is not necessarily enough.

Tgr