How to check if a file exists from a url
Asked Answered
V

8

64

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?

Venge answered 7/10, 2011 at 8:32 Comment(1)
You can use this function getimagesize("url"); . Ref: php.net/manual/en/function.getimagesize.phpHighspeed
S
85

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;
}
Satterfield answered 7/10, 2011 at 8:41 Comment(4)
You don't need CURL for that... way too much overhead... check my answer below (use PHP's get_headers for this!)Photophobia
like the others it's too, not checking whether it's a file or not, just checking the URL. echo is_url_exists('http://stackoverflow.com') ? 'Yes' : 'No'; echoed Yes.Objectivism
this was not working for me until I added the CURLOPT_FOLLOWLOCATION,true directiveJessejessee
The function name should be does_url_exists ;)Farrish
P
117

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";
Photophobia answered 18/4, 2015 at 8:36 Comment(6)
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.Yingyingkow
@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.Photophobia
@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('example.com');Coralline
answer is old but very usefulJean
Example of using a HEAD request, as mentioned by @AD7six: php.net/manual/en/function.get-headers.phpKirkcudbright
it's work correctly but if $url is an invalid url you will have error so you can use below code at first of function: if(filter_var($url, FILTER_VALIDATE_URL) === FALSE) return false;Tremayne
S
85

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;
}
Satterfield answered 7/10, 2011 at 8:41 Comment(4)
You don't need CURL for that... way too much overhead... check my answer below (use PHP's get_headers for this!)Photophobia
like the others it's too, not checking whether it's a file or not, just checking the URL. echo is_url_exists('http://stackoverflow.com') ? 'Yes' : 'No'; echoed Yes.Objectivism
this was not working for me until I added the CURLOPT_FOLLOWLOCATION,true directiveJessejessee
The function name should be does_url_exists ;)Farrish
T
21

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/

Therine answered 24/7, 2013 at 14:19 Comment(7)
Did you mean getimagesize? As here: uk1.php.net/getimagesize if so then the docs say it can reference local or remote files.Lichen
getimagesize is way too much overhead. If you just want to know if a file exists use PHP's get_header (check my answer)Photophobia
It is not much bad ,but it is just worked for images!Breve
I agree with patrick this is not a solution, I hope not too many ppl used this method.Mceachern
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.Burushaski
@herbert. All depends on how many times this will be called and how many times people will be using this...Photophobia
@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.Carlcarla
J
13

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;
}
Jokester answered 29/8, 2016 at 14:31 Comment(0)
K
2

You can use the function file_get_contents();

if(file_get_contents('https://example.com/example.txt')) {
    //File exists
}
Kirkuk answered 17/10, 2018 at 13:38 Comment(3)
It will slow down your application and increase TTFB ( Time To Take First Byte ). So Never use this function.Unitary
it takes all content of file ... if you want to check large files , it will get too timeLiquidator
It will also break your page if url is wrong.. I mean no file exist on a given path.Kus
F
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.

Flicker answered 7/10, 2011 at 8:34 Comment(0)
S
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;
} 
Sadiron answered 14/5, 2021 at 11:25 Comment(0)
S
-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> 
    <? }
    ?>
Striker answered 26/5, 2020 at 8:7 Comment(1)
Welcome to Stack Overflow! Please see How to 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.Longinus

© 2022 - 2024 — McMap. All rights reserved.