FILTER_SANITIZE_URL

$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.

This function removes all chars except letters, digits and $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=.

Example

$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

Example 2: Sanitizing User-Submitted URLs

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>

Example 3: Validating and Sanitizing a URL

$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";
}

Example 4: Handling Malformed URLs

$malformed_url = "http://example.com/some page";
$sanitized_url = filter_var($malformed_url, FILTER_SANITIZE_URL);
echo $sanitized_url; // Outputs: http://example.com/somepage

Filter reference Validating URL Validating Boolean data Ctype_alnum to check alphanumeric characters Validating Email address
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here





    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer