FILTER_SANITIZE_URL removes characters not permitted by that filter, but sanitizing does not prove that the result is a valid or trusted URL. Validate the result separately.
$raw = 'https://example.com/docs?page=2';
$clean = filter_var($raw, FILTER_SANITIZE_URL);
$valid = filter_var($clean, FILTER_VALIDATE_URL);
var_dump($valid);
$url = "https://www.plus 2 net.com ";
echo $url;
$url_new= filter_var($url, FILTER_SANITIZE_URL);
echo "<br> After FILTER_SANITIZE_URL : $url_new ";
Output is here ( space is removed )
https://www.plus 2 net.com
After FILTER_SANITIZE_URL : https://www.plus2net.com
We can sanitize a URL by using FILTER_SANITIZE_URL.
$url = 'https://www.plus 2 net.com?id=123&mem=alex_#rt$k';
echo $url;
$url_new= filter_var($url, FILTER_SANITIZE_URL);
echo "<br> After FILTER_SANITIZE_URL : $url_new ";
OUtput is here
https://www.plus 2 net.com?id=123&mem=alex_#rt$k
After FILTER_SANITIZE_URL : https://www.plus2net.com?id=123&mem=alex_#rt$k
The FILTER_SANITIZE_URL filter is used to clean user-submitted URLs, removing harmful characters:
$url = "https://example.com/?id=<script>alert(1)</script>";
$clean_url = filter_var($url, FILTER_SANITIZE_URL);
echo $clean_url; // Check below code.
It is suggestd to also use htmlspecialchars() here.
$url = "https://example.com/?id=<script>alert(1)</script>";
$clean_url = htmlspecialchars(filter_var($url, FILTER_SANITIZE_URL), ENT_QUOTES, 'UTF-8');
echo $clean_url; // Outputs: https://example.com/?id=<script>alert(1)</script>
https://example.com/?id=<script>alert(1)</script>
$url = "https://example.com";
$sanitized_url = filter_var($url, FILTER_SANITIZE_URL);
if (filter_var($sanitized_url, FILTER_VALIDATE_URL)) {
echo "Valid URL";
} else {
echo "Invalid URL";
}
$malformed_url = "http://example.com/some page";
$sanitized_url = filter_var($malformed_url, FILTER_SANITIZE_URL);
echo $sanitized_url; // Outputs: http://example.com/somepage
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.