Custom URL redirect in WP

The problem is with this expression:

filter_var($url, FILTER_VALIDATE_URL) !== true

which should or could be written as just:

filter_var($url, FILTER_VALIDATE_URL)

Because the PHP manual for filter_var() says:

Returns the filtered data, or FALSE if the filter fails.

which means, with a valid URL, filter_var() does not return a boolean; hence filter_var($url, FILTER_VALIDATE_URL) !== true never evaluates to false. I.e. all URLs would be seen as valid.

So the full code, without the comments:

$url = $_GET["URL"];

// Remove all illegal characters from a url
$url = filter_var($url, FILTER_SANITIZE_URL);

if (filter_var($url, FILTER_VALIDATE_URL)) {
    header("location: " . $url);
    exit;
} else {
    echo("$url is not a valid URL");
}

Additional Note

To redirect to an external URL/domain, you need to specify the protocol — e.g. http://. Try below header() code and you’d understand it:

Code #1:

// Has the protocol; this would always redirect to http://www.google.com
header( 'Location: http://www.google.com' );
exit;

Code #2:

// Protocol not specified; redirects to a URL on your site. For example,
// if you're on http://your-site.com/path, then you'd be redirected to
// http://your-site.com/path/www.google.com
header( 'Location: www.google.com' );
exit;