What best practices should be followed when handling user input for URLs to prevent issues with link redirection in PHP applications?

When handling user input for URLs in PHP applications, it is important to sanitize and validate the input to prevent issues with link redirection, such as open redirect vulnerabilities. One way to do this is by using PHP's filter_var() function with the FILTER_VALIDATE_URL filter to ensure the input is a valid URL before using it in a redirect.

// Sanitize and validate user input for URL
$userInput = $_GET['url'] ?? '';
$url = filter_var($userInput, FILTER_VALIDATE_URL);

if ($url !== false) {
    header("Location: $url");
    exit();
} else {
    // Handle invalid URL input
    echo "Invalid URL provided";
}