Search code examples
phpjavascriptjqueryhtmlimagesource

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


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


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.