Rectangle 27 1

How can one check to see if a remote file exists using PHP?


$imageArray = getimagesize("http://www.example.com/image.jpg");
if($imageArray[0])
{
    echo "it's an image and here is the image's info<br>";
    print_r($imageArray);
}
else
{
    echo "invalid image";
}
exif_imagetype

If you are dealing with images, use getimagesize. Unlike file_exists, this built-in function supports remote files. It will return an array that contains the image information (width, height, type..etc). All you have to do is to check the first element in the array (the width). use print_r to output the content of the array

In my case this was the best approach, because I get redirected whenever an image/file doesnt exist. I second that the suppressing errors with @ is a no go but in this case it was neccessary.

Results in 404 warning when the remote resource is not available. For the time being, I handled it by suppressing error using @ in front of getimagesize, but feeling guilty for this hack.

Note
Rectangle 27 1

How can one check to see if a remote file exists using PHP?


function remoteFileExists($url) {
    $curl = curl_init($url);

    //don't fetch the actual page, you only want to check the connection is ok
    curl_setopt($curl, CURLOPT_NOBODY, true);

    //do request
    $result = curl_exec($curl);

    $ret = false;

    //if request did not fail
    if ($result !== false) {
        //if request was ok, check response code
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);  

        if ($statusCode == 200) {
            $ret = true;   
        }
    }

    curl_close($curl);

    return $ret;
}

$exists = remoteFileExists('http://stackoverflow.com/favicon.ico');
if ($exists) {
    echo 'file exists';
} else {
    echo 'file does not exist';   
}

As Pies say you can use cURL. You can get cURL to only give you the headers, and not the body, which might make it faster. A bad domain could always take a while because you will be waiting for the request to time-out; you could probably change the timeout length using cURL.

remoteFileExists('stackoverflow.com/') this will also returns true, but its just a link. This function not checking is the link content type are file.

Note
Rectangle 27 1

How can one check to see if a remote file exists using PHP?


IMAGETYPE_XXX
exif_imagetype
if (@exif_imagetype($filename)) {
  // Image exist
}
image_type_to_extension
image_type_to_mime_type

To check for the existence of images, exif_imagetype should be preferred over getimagesize, as it is much faster.

To suppress the E_NOTICE, just prepend the error control operator (@).

Note
Rectangle 27 1

How can one check to see if a remote file exists using PHP?


function remoteFileExists($url) {
    $curl = curl_init($url);

    //don't fetch the actual page, you only want to check the connection is ok
    curl_setopt($curl, CURLOPT_NOBODY, true);

    //do request
    $result = curl_exec($curl);

    $ret = false;

    //if request did not fail
    if ($result !== false) {
        //if request was ok, check response code
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);  

        if ($statusCode == 200) {
            $ret = true;   
        }
    }

    curl_close($curl);

    return $ret;
}

$exists = remoteFileExists('http://stackoverflow.com/favicon.ico');
if ($exists) {
    echo 'file exists';
} else {
    echo 'file does not exist';   
}

As Pies say you can use cURL. You can get cURL to only give you the headers, and not the body, which might make it faster. A bad domain could always take a while because you will be waiting for the request to time-out; you could probably change the timeout length using cURL.

remoteFileExists('stackoverflow.com/') this will also returns true, but its just a link. This function not checking is the link content type are file.

Note
Rectangle 27 1

How can one check to see if a remote file exists using PHP?


<img src="http://www.google.com/s2/favicons?domain=[domain]">

Instead of actually trying to get the site's favicon directly (which is a royal pain given it could be /favicon.png, /favicon.ico, /favicon.gif, or even /path/to/favicon.png), use google:

This is not an answer to your original question, but a better way of doing what you're trying to do:

Note
Rectangle 27 1

How can one check to see if a remote file exists using PHP?


$file = 'http://mysite.co.za/images/favicon.ico';
$file_exists = (@fopen($file, "r")) ? true : false;

Worked for me when trying to check if an image exists on the URL

You could use the following:

Note
Rectangle 27 1

How can one check to see if a remote file exists using PHP?


$http_response_header
$url = 'http://example.com/';
$code = FALSE;

$options['http'] = array(
    'method' => "HEAD",
    'ignore_errors' => 1,
    'max_redirects' => 0
);

$body = file_get_contents($url, NULL, stream_context_create($options));

sscanf($http_response_header[0], 'HTTP/%*d.%*d %d', $code);

echo "Status code: $code";

@Erikerpnjak: If there is "no custom" stream_context, it's the default one. You can get the options from the default context and take a look how them vary from your custom context. This should give you some insight why timings differ. - php.net/stream-context-get-default and php.net/stream-context-get-options

If you don't want to follow redirects, you can do it similar (Demo):

Some of the functions, options and variables in use are explained with more detail on a blog post I've written: HEAD first with PHP Streams.

The second variant worked for me and compared to the default file_get_contents call (no custom stream_context) it was 50% faster, i.e. from 3,4s to 1,7s for a request.

This can be done by obtaining the HTTP Status code (404 = not found) which is possible with file_get_contentsDocs making use of context options. The following code takes redirects into account and will return the status code of the final destination (Demo):

Note
Rectangle 27 1

How can one check to see if a remote file exists using PHP?


$url=getimagesize(http://www.flickr.com/photos/27505599@N07/2564389539/);

if(!is_array($url))
{
   $default_image =/directoryFolder/junal.jpg;
}

You can use :

Note
Rectangle 27 1

How can one check to see if a remote file exists using PHP?


$ch = curl_init("http://www.example.com/favicon.ico");

curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// $retcode >= 400 -> not found, $retcode = 200, found.
curl_close($ch);

@Lyth 3XX retcodes aren't an error, but a redirection. Those should be either handled manually or using CURLOPT_FOLLOWLOCATION.

Anyway, you only save the cost of the HTTP transfer, not the TCP connection establishment and closing. And being favicons small, you might not see much improvement.

Caching the result locally seems a good idea if it turns out to be too slow. HEAD checks the time of the file, and returns it in the headers. You can do like browsers and get the CURLINFO_FILETIME of the icon. In your cache you can store the URL => [ favicon, timestamp ]. You can then compare the timestamp and reload the favicon.

Some sites block access if you don't provide a user agent string, so I suggest following this guide to add CURLOPT_USERAGENT in addition to CURLOPT_NOBODY: davidwalsh.name/set-user-agent-php-curl-spoof

Use curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); as well to make sure same code works for URL's starting with HTTPS!

You can instruct curl to use the HTTP HEAD method via CURLOPT_NOBODY.

just a note: retcode errors on all 400 codes so the validation would be >= not just >

Note
Rectangle 27 1

How can one check to see if a remote file exists using PHP?


function remote_file_exists($url){
   return(bool)preg_match('~HTTP/1\.\d\s+200\s+OK~', @current(get_headers($url)));
}  
$ff = "http://www.emeditor.com/pub/emed32_11.0.5.exe";
    if(remote_file_exists($ff)){
        echo "file exist!";
    }
    else{
        echo "file not exist!!!";
    }
Note