best way to determine if a URL is an image in PHP

You could use an HTTP HEAD request and check the content-type. This might be a good compromise. It can be done using PHP Streams. Wez Furlong has an article that shows how to use this approach to send post requests, but it can be easily adapted to send HEAD requests instead. You can retrieve the headers from an http response using stream_get_meta_data().

Of course this isn’t really 100%. Some servers send incorrect headers. It will however handle cases where images are delivered through a script and the correct file extension isn’t available. The only way to be really certain is to actually retrieve the image – either all of it, or the first few bytes, as suggested by thomasrutter.

Leave a Comment