tags:

views:

133

answers:

2

I am trying to prevent xss injection. So before I submit a form, a javascript function is called

function validatefield(id) {
    var description = document.getElementById(id).value;   
    description = description.replace(/[\"\'][\s]*javascript:(.*)[\"\']/gi, "");
    description = description.replace(/script(.*)/gi, "");    
    description = description.replace(/eval\((.*)\)/gi, "");
    document.getElementById(id).value=description;
} 

I am wonderng if there's a way to do the same in php before inserting into the mysql? if they get around of the validatefield function.

Thanks

+4  A: 

You are looking for preg_replace.

$description = preg_replace('regex pattern', 'regex replacement', $description);
Chris Clarke
Regular expressions are poorly suited for (non-regular) html syntax. You'd also have to run that until it didn't find any more matches to replace in order to take care of sitauations like <<scriptscript...
jasonbar
I tried to just copy and paste the js version but it doesnt seem to work$text = preg_replace('/[\"\'][\s]*javascript:(.*)[\"\']/gi', '', $text);$text = preg_replace('/script(.*)/gi', '', $text); $text = preg_replace('/eval\((.*)\)/gi', '', $text);
hao
The regular expression dialect is different. This function only accepts Perl Compatible Regular Expressions. Here is a cheat sheet:http://www.phpguru.org/downloads/PCRE%20Cheat%20Sheet/PHP%20PCRE%20Cheat%20Sheet.pdfYou will need to rewrite your regular expressions for them to work in PHP.
Chris Clarke
+3  A: 

Generally speaking, you can use preg_replace for regex replacements in PHP. But there are a few problems with your design

  1. You shouldn't even bother doing this on the client. It will slow things down without providing security.
  2. You're removing things that are perfectly safe (e.g. "I wrote a script to do such as such"), while ignoring many actual dangers like onclick attributes (see also XSS Cheat Sheet).

Generally speaking, if you want to allow some form of HTML, a whitelist is a better approach. HTML Purifier is a popular tool for implementing this in PHP.

Matthew Flaschen
+1 for html purifier and white lists. Boo! for regular expresions and html.
jasonbar