What are the best practices for handling URLs in PHP, specifically in relation to security?

When handling URLs in PHP, it is important to sanitize and validate user input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. One way to do this is by using PHP's filter_var() function with the FILTER_VALIDATE_URL flag to validate URLs. Additionally, it is recommended to use prepared statements when interacting with a database to avoid SQL injection attacks.

// Example of sanitizing and validating a URL input
$url = filter_var($_GET['url'], FILTER_VALIDATE_URL);

if ($url === false) {
    // Invalid URL, handle error
} else {
    // Valid URL, proceed with processing
}