What is the purpose of filtering URLs from source code in PHP?

Filtering URLs from source code in PHP is important for security reasons to prevent malicious code injections or attacks such as cross-site scripting (XSS). By filtering URLs, you can ensure that only valid and safe URLs are allowed in your code, reducing the risk of vulnerabilities.

// Example code to filter URLs from source code in PHP

$url = "https://example.com";
$filtered_url = filter_var($url, FILTER_VALIDATE_URL);

if($filtered_url){
    // URL is valid, proceed with using it in your code
    echo "Valid URL: " . $filtered_url;
} else {
    // URL is invalid, handle the error accordingly
    echo "Invalid URL";
}