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
Selected Reading
FILTER_SANITIZE_URL constant in PHP
The FILTER_SANITIZE_URL constant removes all illegal URL characters from a string, keeping only characters that are valid in URLs. This filter is useful for cleaning user input before using it in URL contexts.
Allowed Characters
The FILTER_SANITIZE_URL filter allows the following characters −
$-_.+!*'(),{}|\^~[]`"><#%;/?:@&=
All other characters, including spaces and non-ASCII characters, will be removed from the input string.
Syntax
filter_var($string, FILTER_SANITIZE_URL)
Parameters
- $string − The string to be sanitized
- FILTER_SANITIZE_URL − The filter constant
Return Value
Returns the sanitized string with illegal URL characters removed, or FALSE on failure.
Examples
Basic URL Sanitization
<?php
$var = "www.example.com";
var_dump(filter_var($var, FILTER_SANITIZE_URL));
?>
string(15) "www.example.com"
Removing Invalid Characters
<?php
$url = "https://example.com/search?q=hello world&type=web";
$sanitized = filter_var($url, FILTER_SANITIZE_URL);
echo "Original: " . $url . "<br>";
echo "Sanitized: " . $sanitized;
?>
Original: https://example.com/search?q=hello world&type=web Sanitized: https://example.com/search?q=helloworld&type=web
Key Points
- Spaces are removed from the input string
- Non-ASCII characters are stripped out
- Valid URL characters like
://,?,&, and=are preserved - This filter does not validate URLs, only sanitizes them
Conclusion
The FILTER_SANITIZE_URL constant is useful for cleaning strings that will be used as URLs by removing illegal characters while preserving valid URL syntax characters.
Advertisements
