How to check if a file exists from a url

David picture David · Oct 7, 2011 · Viewed 126.7k times · Source

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?

Answer

patrick picture patrick · Apr 18, 2015

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