How can the get_headers function be used to check for the existence of an external file in PHP?

To check for the existence of an external file in PHP, you can use the get_headers function to retrieve the headers of the file's URL. If the file exists, the function will return an array containing the headers, including the HTTP response code. You can then check if the response code is 200, which indicates that the file exists.

$url = 'http://www.example.com/file.txt';
$headers = get_headers($url);

if(strpos($headers[0], '200') !== false){
    echo 'File exists.';
} else {
    echo 'File does not exist.';
}