Preventing cross-site-scripting (XSS) vulnerability

Recently i came across a report at, about being vulnerable to cross site scripting (XSS). That report was filed way back in 2009, and we have already fixed that when we upgraded in 2010.

I wanted to share the code we used to check the input from users to possibly prevent XSS vulnerability.

// cross-site-scripting (XSS) vulnerability
$q = $_GET["q"];
//remove the script tag and its contents
$q = preg_replace('/]*>([\s\S]*?)<\/script[^>]*>/', '', $q);
// remove any special chars - if you need them, then you can skip this step.
$q = preg_replace('/[^a-zA-Z-,\s]/', '', $q);

This will ensure you minimize the risk.

Please do share your thoughts.