1

I want to check if a file exists on a remote webserver with php.

I now have this function:

function url_exists($url) {
   // Version 4.x supported
   $handle   = curl_init($url);
   if (false === $handle)
   {
       return false;
   }
   curl_setopt($handle, CURLOPT_HEADER, false);
   curl_setopt($handle, CURLOPT_FAILONERROR, true);  // this works
   curl_setopt($handle, CURLOPT_HTTPHEADER, Array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15") ); 
    // request as if Firefox    
    curl_setopt($handle, CURLOPT_NOBODY, true);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
    $connectable = curl_exec($handle);
    curl_close($handle);
    return $connectable;
}

It works fine, but if I pass an ip address instead of a domain name it returns false.. (so I want to check http://123.456.789.121/test.jpg, when I send http://somedomain.com/test.jpg it works fine...)

Any ideas?

Thanks in advance!

CyberK
  • 1,568
  • 3
  • 31
  • 44
  • Have you tried it in your browser (IP address)? – Ruel Nov 21 '10 at 01:30
  • Why on earth do you want to pass an IP address? – SLaks Nov 21 '10 at 01:30
  • Yes I've tried it in my browser, and I want to pass an IP address because that's the only address my app knows. The url's are loaded dynamically so it can be a domain or it can be an ip address. It's just to check if the file exists... – CyberK Nov 21 '10 at 01:31
  • Don't you need to add the port (:8080) when using an IP address ? – Ephi Aug 17 '16 at 12:34

1 Answers1

3

The remote server probably resolves files using the Host header.
If so, you need to use a domain name.

You may be able to explicitly pass a Host header to the IP address, but I wouldn't recommend it.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • And how can I pass a Host header? :D – CyberK Nov 21 '10 at 01:50
  • @CyberK, you can add your own headers to the CURL_HTTPHEADER option, for example: `curl_setopt($handle, CURLOPT_HTTPHEADER, Array("Host: www.example.com", "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15") );` – BrianC Jan 04 '12 at 19:29