Home » Php » php – How to check if a file exists from a url

php – How to check if a file exists from a url

Posted by: admin April 23, 2020 Leave a comment

Questions:

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?

How to&Answers:

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;
}

Answer:

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";

Answer:

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/

Answer:

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;
}

Answer:

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.

Answer:

You can use the function file_get_contents();

if(file_get_contents('https://example.com/example.txt')) {
    //File exists
}