Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
FILTER_SANITIZE_STRING constant in PHP
The FILTER_SANITIZE_STRING constant removes HTML tags and encodes special characters from a string. This filter is useful for cleaning user input to prevent XSS attacks.
Note: As of PHP 8.1.0, FILTER_SANITIZE_STRING is deprecated. Use htmlspecialchars() or custom validation instead.
Syntax
filter_var($value, FILTER_SANITIZE_STRING, $flags)
Flags
FILTER_FLAG_NO_ENCODE_QUOTES − Do not encode quotes
FILTER_FLAG_STRIP_LOW − Removes characters with ASCII value less than 32
FILTER_FLAG_STRIP_HIGH − Removes characters with ASCII value greater than 127
FILTER_FLAG_ENCODE_LOW − Encodes characters with ASCII value less than 32
FILTER_FLAG_ENCODE_HIGH − Encodes characters with ASCII value greater than 127
FILTER_FLAG_ENCODE_AMP − Encodes the "&" character to &
Return Value
Returns the sanitized string on success, or FALSE on failure.
Example
The following example demonstrates removing HTML tags and high ASCII characters ?
<?php $var = "<p>£Demo! ££</p>"; $res = filter_var($var, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); echo $res; ?>
The output of the above code is ?
Demo!
Using Multiple Flags
You can combine multiple flags using the bitwise OR operator ?
<?php
$input = "<script>alert('test')</script>Hello World!";
$clean = filter_var($input, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_ENCODE_AMP);
echo $clean;
?>
The output of the above code is ?
Hello World!
Conclusion
FILTER_SANITIZE_STRING provides basic string sanitization by removing HTML tags and encoding special characters. However, since it's deprecated in PHP 8.1+, consider using htmlspecialchars() for modern applications.
