Prevent XSS (Cross Site Scripting) in PHP.

If your site takes card payments, chances are you need to take and pass some sort of regular security test to keep your online banking provider happy.

This is the case for us, and running most of our front end on CodeIgniter, we discovered the inbuilt xss_clean functionality, while it does actually does the job, is not enough to appease the folks who run the security scans on our sites.

So. Here is a quick function to help anyone else stuck in the same situation. The extra iteration is to deal with form submissions containing checkboxes, otherwise htmlspecialchars() would bail out with an error when we unexpectedly pass it an array instead of a string!

You just need to run this function somewhere at the start of all your code. If you’re using CodeIgniter too, pop it at the top of your MY_Controller’s constructor.

function stopXSS() {
// prevent XSS on $_GET, $_POST and $_COOKIE
foreach ($_GET as $gkey => &$gval) {
if(is_array($gval)) { // allow for checkboxes!
foreach ($gval as $gkey2 => &$gval2) {
$gval2 = htmlspecialchars($gval2);
}
} else {
$gval = htmlspecialchars($gval);
}
}
foreach ($_POST as $pkey => &$pval) {
if(is_array($pval)) { // allow for checkboxes!
foreach ($pval as $pkey2 => &$pval2) {
$pval2 = htmlspecialchars($pval2);
}
} else {
$pval = htmlspecialchars($pval);
}
}
foreach ($_COOKIE as $ckey => &$cval) {
$cval = htmlspecialchars($cval);
}
}

Leave a Reply