What are the best practices for handling PHP URLs to avoid unexpected behavior?

When handling PHP URLs, it is important to properly sanitize and validate user input to prevent unexpected behavior such as SQL injection or cross-site scripting attacks. One way to do this is by using PHP's built-in filter functions to validate and sanitize input data.

// Example of sanitizing and validating a URL parameter
$url = filter_input(INPUT_GET, 'url', FILTER_SANITIZE_URL);

if (filter_var($url, FILTER_VALIDATE_URL)) {
    // URL is valid, proceed with further processing
} else {
    // Invalid URL, handle error accordingly
}