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


The best I could find, an if fclose fopen type thing, makes the page load really slowly.

Basically what I'm trying to do is the following: I have a list of websites, and I want to display their favicons next to them. However, if a site doesn't have one, I'd like to replace it with another image rather than display a broken image.

11/14/2011 11:42:03 PM

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

More or less

$ch = curl_init("");

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

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.

10/14/2013 2:42:32 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow