File_Exists For Remote URL

If you want to make sure that a file exists in PHP you can use the function file_exists(), which takes one parameter of the filename.
// Returns true if the file exists
file_exists( $filename );
This function will not only work for files but will also work for directories, you can pass in a filename of the directory and if this directory exists the file_exists() function will return true.
<?php
$filename = '/path/to/foo.txt';

if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}
?>
The problem I've seen with this function is that people have tried to use it when they want to see if a remote file exists using a URL. But if you try to search for a file exists using this function with a URL it will not work correctly, the function will always return false.
If you want to check if the file_exists() with a remote URL you need to make a HTTP request for this file and check what the HTTP header status are when the request returns.

Get Headers Of A URL

To get the headers of a remote file then you can use the PHP function of get_headers(). This takes a parameter of the URL you want to request and it will return an array of the headers returned. The first key of the array is the value we are interested in, this will return the header status of the HTTP. If the file exists the status will return a 200 code, if the remote file doesn't exist then the status will return a 404 error.
This means we can use function to check if the remote file exists.
$file_headers = @get_headers($url);
if($file_headers[0] == 'HTTP/1.0 404 Not Found')
{
   $file_exists = false;
} else {
   $file_exists = true;
}

No comments:

Post a Comment