prevent xss attack via url( PHP)

Rajeev Ranjan picture Rajeev Ranjan · Jun 3, 2013 · Viewed 7.2k times · Source

I am trying to avoid XSS attack via url
url :http://example.com/onlineArcNew/html/terms_conditions_1.php/%22ns=%22alert%280x0000DC%29 I have tried

var_dump(filter_var('http://10.0.4.2/onlineArcNew/html/terms_conditions_1.php/%22ns=%22alert%280x0000DC%29', FILTER_VALIDATE_URL));

and other url_validation using regex but not worked at all. above link shows all the information but my css and some java script function doesn't work. please suggest the best possible solution...

Answer

Baba picture Baba · Jun 3, 2013

Try using FILTER_SANITIZE_SPECIAL_CHARS Instead

$url = 'http://10.0.4.2/onlineArcNew/html/terms_conditions_1.php/%22ns=%22alert%280x0000DC%29';

// Original
echo $url, PHP_EOL;

// Sanitise
echo sanitiseURL($url), PHP_EOL;

// Satitise + URL encode
echo sanitiseURL($url, true), PHP_EOL;

Output

http://10.0.4.2/onlineArcNew/html/terms_conditions_1.php/%22ns=%22alert%280x0000DC%29
http://10.0.4.2/onlineArcNew/html/terms_conditions_1.php/"ns="alert(0x0000DC)
http%3A%2F%2F10.0.4.2%2FonlineArcNew%2Fhtml%2Fterms_conditions_1.php%2F%26%2334%3Bns%3D%26%2334%3Balert%280x0000DC%29

Function Used

function sanitiseURL($url, $encode = false) {
    $url = filter_var(urldecode($url), FILTER_SANITIZE_SPECIAL_CHARS);
    if (! filter_var($url, FILTER_VALIDATE_URL))
        return false;
    return $encode ? urlencode($url) : $url;
}