FILTER_SANITIZE_SPECIAL_CHARS constant in PHP

The FILTER_SANITIZE_SPECIAL_CHARS constant filter HTML-escapes special characters like <, >, &, and quotes to prevent XSS attacks and ensure safe display in HTML.

Syntax

filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS, $flags)

Flags

  • FILTER_FLAG_STRIP_LOW − Strip characters with ASCII value below 32

  • FILTER_FLAG_STRIP_HIGH − Strip characters with ASCII value above 127

  • FILTER_FLAG_ENCODE_HIGH − Encode characters with ASCII value above 127

Return Value

Returns the sanitized string with special characters HTML-encoded, or FALSE on failure.

Example

Here's how to sanitize a string containing HTML special characters ?

<?php
    $var = "Favorite Sports is Football & Cricket? <script>alert('XSS')</script>";
    $sanitized = filter_var($var, FILTER_SANITIZE_SPECIAL_CHARS);
    echo "Original: " . $var . "<br>";
    echo "Sanitized: " . $sanitized;
?>
Original: Favorite Sports is Football & Cricket? <script>alert('XSS')</script>
Sanitized: Favorite Sports is Football & Cricket? <script>alert('XSS')</script>

Using Flags

Example showing how flags modify the sanitization behavior ?

<?php
    $text = "Hello & Goodbye\x08\xFF";
    
    echo "Original: " . $text . "<br>";
    echo "Default: " . filter_var($text, FILTER_SANITIZE_SPECIAL_CHARS) . "<br>";
    echo "Strip Low: " . filter_var($text, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_LOW) . "<br>";
    echo "Strip High: " . filter_var($text, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_HIGH) . "<br>";
?>
Original: Hello & Goodbye
Default: Hello & Goodbye
Strip Low: Hello & Goodbye
Strip High: Hello & Goodbye

Conclusion

FILTER_SANITIZE_SPECIAL_CHARS is essential for preventing XSS attacks by converting dangerous HTML characters into safe entities. Use it when displaying user input in HTML contexts.

Updated on: 2026-03-15T07:35:08+05:30

885 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements