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_ENCODED constant in PHP
The FILTER_SANITIZE_ENCODED constant in PHP is used with the filter_var() function to URL-encode special characters in a string. This is particularly useful for sanitizing URLs and ensuring they contain only valid characters.
Syntax
filter_var($value, FILTER_SANITIZE_ENCODED, $flags)
Flags and Options
FILTER_FLAG_STRIP_LOW − Remove characters with ASCII value less than 32
FILTER_FLAG_STRIP_HIGH − Remove characters with ASCII value greater than 127
FILTER_FLAG_ENCODE_LOW − Encode characters with ASCII value less than 32
FILTER_FLAG_ENCODE_HIGH − Encode characters with ASCII value greater than 127
Return Value
The filter_var() function with FILTER_SANITIZE_ENCODED returns the sanitized string with special characters URL-encoded, or FALSE on failure.
Basic Example
Here's a simple example showing how FILTER_SANITIZE_ENCODED URL-encodes special characters −
<?php
$string = "Hello World! @#$%";
$encoded = filter_var($string, FILTER_SANITIZE_ENCODED);
echo $encoded;
?>
Hello%20World%21%20%40%23%24%25
Using FILTER_FLAG_STRIP_HIGH
The following example uses FILTER_FLAG_STRIP_HIGH flag to remove characters with ASCII value greater than 127 −
<?php
$url = "wwwÅ.exampleÅ.com";
$sanitized = filter_var($url, FILTER_SANITIZE_ENCODED, FILTER_FLAG_STRIP_HIGH);
echo $sanitized;
?>
www.example.com
Another Example with Special Characters
Let's see another example with different special characters −
<?php
$url = "example.com££";
$sanitized = filter_var($url, FILTER_SANITIZE_ENCODED, FILTER_FLAG_STRIP_HIGH);
echo $sanitized;
?>
example.com
Using Multiple Flags
You can combine multiple flags using the bitwise OR operator −
<?php
$string = "Test\x01StringÅ";
$result = filter_var($string, FILTER_SANITIZE_ENCODED,
FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
echo $result;
?>
TestString
Conclusion
The FILTER_SANITIZE_ENCODED constant is essential for URL sanitization, encoding special characters and optionally removing unwanted ASCII characters. Use appropriate flags based on your specific requirements for character handling.
