XSS filtering function in PHP
Here is an example of a basic XSS filtering function in PHP:
<?php
/**
* Function to filter potential XSS attacks
* @param string $data - The input data to be filtered
* @return string - The filtered data
*/
function xss_filter($data)
{
// Remove any non-printable characters
$data = preg_replace('/[\x00-\x1F\x7F]/', '', $data);
// Remove any characters that are not allowed in HTML
$data = preg_replace('/[<>\?\'\"\(\)\[\]]/', '', $data);
// Remove any characters that are used for XSS attacks
$data = str_replace(['<', '>', '\'', '\"', ')', '('], '', $data);
// Return the filtered data
return $data;
}
// Example usage
$input = "<script>alert('XSS Attack');</script>";
$output = xss_filter($input);
echo $output;
?>
Watch a video course
Learn object oriented PHP