What are the best practices for handling file_exists function in PHP when dealing with URL wrappers?

When dealing with URL wrappers in PHP, it's important to be cautious when using the file_exists function as it can be vulnerable to directory traversal attacks. To handle this securely, it's recommended to sanitize the input and validate the URL before passing it to the file_exists function.

$url = 'http://example.com/file.txt';
if (filter_var($url, FILTER_VALIDATE_URL)) {
    if (file_exists($url)) {
        echo 'File exists!';
    } else {
        echo 'File does not exist.';
    }
} else {
    echo 'Invalid URL.';
}