PHP: does a remote file exist?



  • I have a database of images, some local, some hosted on photobucket and elsewhere.

    If the image needs resizing (eg, a thumbnail), it checks for a cached version (creates one if needed), and uses HTTP-302 to point the browser there. My problem is that I can't use file_exists() to check whether remotely hosted exist or not; I'm not sure of the mechanics of fopen(), which can handle remote URLs, but I'd rather keep the script as lightweight as possible.


    Any ideas? 



  • In case it's not clear, the script always ends with a HTTP-302; if an error occurs (file not found, no space for creating thumbnail), it'll redirect to an error-image.



  • There's very little you can do, unless you have access to the remote file system and can write a script for whether or not the file exists there. 

    Your best bet is to exploit HTTP knowledge. use fsockopen() to open a socket on the remote system, port 80 (assuming their web server is on the standard port 80). Issue a HEAD request and parse the reply. If you get 404d, it doesn't exist.

    There is a flaw -- you have to connect to the remote host, and if there's a network issue between your server and that server, performance can suffer. It's little different than connecting to a remote database, really, but this is for image service and you want speed in such a circumstance.



  • @Whiskey Tango Foxtrot? Over. said:

    There's very little you can do, unless you have access to the remote file system and can write a script for whether or not the file exists there. 

    Your best bet is to exploit HTTP knowledge. use fsockopen() to open a socket on the remote system, port 80 (assuming their web server is on the standard port 80). Issue a HEAD request and parse the reply. If you get 404d, it doesn't exist.

    There is a flaw -- you have to connect to the remote host, and if there's a network issue between your server and that server, performance can suffer. It's little different than connecting to a remote database, really, but this is for image service and you want speed in such a circumstance.

     Also, don't forget to handle redirects and retry apropriately if the server sends back a 'document moved', not to mention all the other quirks of HTTP/1.1. It's much better to just use a library (libcurl?) for HTTP rather than raw sockets.
     


Log in to reply