What are the best practices for handling URL redirection and validation in PHP scripts?

When handling URL redirection and validation in PHP scripts, it is important to ensure that the URLs being redirected to are valid and secure to prevent potential security vulnerabilities such as open redirects or injection attacks. One best practice is to sanitize and validate user input before using it in a redirection function to ensure that only safe and expected URLs are allowed.

// Example of validating and redirecting to a URL in PHP

// Validate the URL input
$url = filter_var($_GET['url'], FILTER_VALIDATE_URL);

// Check if the URL is valid
if ($url !== false) {
    // Perform the redirection
    header("Location: $url");
    exit;
} else {
    // Handle invalid URL input
    echo "Invalid URL";
}