58

I need to check if a particular file exists on a remote server. Using is_file() and file_exists() doesn't work. Any ideas how to do this quickly and easily?

Ruben
  • 4,655
  • 2
  • 20
  • 43
David
  • 14,182
  • 34
  • 96
  • 150
  • 3
    You can use this function getimagesize("url"); . Ref: http://php.net/manual/en/function.getimagesize.php – InventorX Dec 09 '14 at 07:55

8 Answers8

101

You don't need CURL for that... Too much overhead for just wanting to check if a file exists or not...

Use PHP's get_header.

$headers=get_headers($url);

Then check if $result[0] contains 200 OK (which means the file is there)

A function to check if a URL works could be this:

function UR_exists($url){
   $headers=get_headers($url);
   return stripos($headers[0],"200 OK")?true:false;
}

/* You can test a URL like this (sample) */
if(UR_exists("http://www.amazingjokes.com/"))
   echo "This page exists";
else
   echo "This page does not exist";
patrick
  • 10,664
  • 7
  • 58
  • 75
  • 2
    `By default get_headers uses a GET request to fetch the headers` - so instead of the overhead of a curl request (not really sure what overhead is being referred to by that) - there's a wasteful GET request which drops the body - instead of using a HEAD request and only receiving the headers. – AD7six Jul 03 '15 at 18:36
  • 3
    @AD7six: I was assuming setting up cURL in memory would cause overload, I did some testing comparing the two methods and you're right: if you have the cURL library loaded it's consistently faster to use the accepted method compared to get_headers. I compared all 3 mentioned methods: cURL is the fastest, then get_headers, then getimagesize with the added downside getimagesize will only tell you if an image exists. It is what was asked, so it's still a valid answer here, but it's not very versatile. – patrick Jul 06 '15 at 15:19
  • 1
    @ad7six are you sure get_headers is requesting the body? fyi, you can override the GET request via stream context: stream_context_set_default(['http' => ['method' => 'HEAD']]); $headers = get_headers('http://example.com'); – Toby Jan 29 '16 at 15:59
  • answer is old but very useful – james Oduro Jan 15 '19 at 03:09
  • Example of using a HEAD request, as mentioned by @AD7six: https://www.php.net/manual/en/function.get-headers.php – Genki Jul 05 '20 at 04:08
83

You have to use CURL

function does_url_exists($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($code == 200) {
        $status = true;
    } else {
        $status = false;
    }
    curl_close($ch);
    return $status;
}
Dharman
  • 21,838
  • 18
  • 57
  • 107
Amila
  • 1,303
  • 1
  • 10
  • 17
17

I've just found this solution:

if(@getimagesize($remoteImageURL)){
    //image exists!
}else{
    //image does not exist.
}

Source: http://www.dreamincode.net/forums/topic/11197-checking-if-file-exists-on-remote-server/

Daniel Kossmann
  • 313
  • 2
  • 4
  • Did you mean `getimagesize`? As here: http://uk1.php.net/getimagesize if so then the docs say it can reference local or remote files. – Todd Jan 26 '14 at 18:41
  • 3
    getimagesize is way too much overhead. If you just want to know if a file exists use PHP's get_header (check my answer) – patrick Apr 18 '15 at 08:39
  • It is not much bad ,but it is just worked for images! – ganji Sep 13 '15 at 14:59
  • I agree with patrick this is not a solution, I hope not too many ppl used this method. – ekerner Jan 16 '16 at 02:22
  • However, a single line command is easier for me to read/write/maintain than doing the check with curl. Programmer's time is much more expensive than cpu time, so one has to find the proper balance. – Herbert Van-Vliet Mar 06 '16 at 14:49
  • 1
    @herbert. All depends on how many times this will be called and how many times people will be using this... – patrick Jul 02 '16 at 01:30
  • @HerbertVan-Vliet then write a short function. getimagesize is a hack and doesn't signal intent to future developers. It also triggers a warning when no image is found: `If accessing the filename image is impossible getimagesize() will generate an error of level E_WARNING.` – Armstrongest Oct 11 '17 at 16:57
11

Hi according to our test between 2 different servers the results are as follows:

using curl for checking 10 .png files (each about 5 mb) was on average 5.7 secs. using header check for the same thing took average of 7.8 seconds!

So in our test curl was much faster if you have to check larger files!

our curl function is:

function remote_file_exists($url){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if( $httpCode == 200 ){return true;}
    return false;
}

here is our header check sample:

function UR_exists($url){
   $headers=get_headers($url);
   return stripos($headers[0],"200 OK")?true:false;
}
Daniel de coder
  • 111
  • 1
  • 3
1

You can use the function file_get_contents();

if(file_get_contents('https://example.com/example.txt')) {
    //File exists
}
Tom
  • 60
  • 7
1

Do a request with curl and see if it returns a 404 status code. Do the request using the HEAD request method so it only returns the headers without a body.

fivedigit
  • 17,324
  • 6
  • 50
  • 58
0
$file = 'https://picsum.photos/200/300';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    $exists = false;
}
else {
    $exists = true;
} 
Optimaz ID
  • 391
  • 3
  • 9
-1
    $headers = get_headers((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER[HTTP_HOST] . '/uploads/' . $MAIN['id'] . '.pdf');
    $fileExist = (stripos($headers[0], "200 OK") ? true : false);
    if ($fileExist) {
    ?>
    <a class="button" href="/uploads/<?= $MAIN['id'] ?>.pdf" download>скачать</a> 
    <? }
    ?>
Adriaan
  • 15,941
  • 7
  • 35
  • 67
  • 2
    Welcome to Stack Overflow! Please see [answer]. Always remember when answering a question you're not only answering to the OP, but also to future readers *especially* when answering 9 year old question. Thus, please [edit] the post to contain an explanation as to **why** this code works. – Adriaan May 26 '20 at 08:10