Question

What is the best way to detect that a URL is that of an image?

Was it helpful?

Solution

Using PHP:

  • Safest - fetch the actual image data. Do a getimagesize() to determine the image type by actually reading the header bytes inside the file.

  • Fastest - fetch the resource, parse the response headers and look for the content-type header. This method is not as reliable as the first one: The server could be lying, or misconfigured.

  • Even faster - do a HEAD request on the URL, and look for the content-type header. May not work for dynamic image resources. I have no experience with this, so mileage may vary.

  • Ultra-paranoid safest but slooow - fetch the actual image data using PHP, copy them into a new image resource using the GD library, and save the result. If this process works out, it is guaranteed to be a valid, untainted image. Resource-intensive; some valid image formats that a browser supports but GD does not will fall under the table.

I'd go for the first option.

Using JavaScript:

  • Load the image resource into an img element. If the onload event fires, and the image has physical dimensions afterwards, the browser managed to load the image.

OTHER TIPS

May be look at the HTTP Headers? Just a thought.

Try to check the headers of the response once you have request an HTTP connection of that URL... try to look for the mime-type.

  • inspect headers
  • check for extension in url(.gif/.png etc)

If you only have the URL rather than the response the server will give you when you request the URL, then the only thing you can do is guess based on the file extension, but there is NO guarantee that a file ending in .jpg is an image or that a file ending in .php is not an image.

You can probably be reasonably happy urls ending in .jpg, .gif, .png etc are going to be images but it is not guaranteed.

For anything else its essentially impossible unless you retrive it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top