What are the best practices for handling URLs in PHP code?

When handling URLs in PHP code, it is important to properly sanitize and validate user input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. It is also recommended to use built-in PHP functions like filter_var() to validate URLs and prevent malicious input. Additionally, encoding and decoding URLs using urlencode() and urldecode() functions can help ensure proper handling of special characters.

// Example of sanitizing and validating a URL input
$url = isset($_GET['url']) ? $_GET['url'] : '';

// Sanitize and validate the URL input
if (filter_var($url, FILTER_VALIDATE_URL)) {
    // URL is valid, proceed with further processing
    $sanitizedUrl = filter_var($url, FILTER_SANITIZE_URL);
    
    // Use the sanitized URL in your code
    echo "Sanitized URL: " . $sanitizedUrl;
} else {
    // URL is not valid, handle the error accordingly
    echo "Invalid URL input";
}