$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