W3docs

XSS filtering function in PHP

Here is an example of a basic XSS filtering function in PHP:

Here is an example of a secure XSS filtering approach in PHP.

Security Warning: Stripping characters from user input is a security anti-pattern. It destroys legitimate data (like <div> or 5 > 3 ) and fails to block many XSS vectors. The standard and secure method is to encode output at the point of rendering using htmlspecialchars() instead of filtering input.

Example of secure XSS prevention in PHP

<?php

/**
 * Securely encode output to prevent XSS
 * @param string $data - The input data to be encoded
 * @return string - The encoded data
 */
function xss_filter($data)
{
    // Encode special characters to HTML entities
    return htmlspecialchars($data, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}

// Example usage
$input = "<script>alert('XSS Attack');</script>";
$output = xss_filter($input);

echo $output;

?>

<div class="alert alert-info flex not-prose">Watch a course <span class="hidden md:block">Watch a video course</span> Learn object oriented PHP </div>