Frage

I would like to check if a remote image is hotlink-protected, or not.

  • If the image is not protected against hotlinking, I would like to display the image. (Don't worry, I will add a visible hyperlink to the source, and I will give the legitimate owner the possibility to remove the image.)
  • If the image is protected, I would do nothing.

Is it possible (with PHP and/or Javascript) to make the distinction between hotlink-protected images and 'hotlinkable' images?

War es hilfreich?

Lösung

Yes, you can definitely do this from PHP. When you want to hotlink the file, create an HTTP connection and set the Referer header in the request to your site. If you get a 200 response with the image data, it is not hotlink protected. If you get a 301 forwarding response it is hotlink protected.

Andere Tipps

It may be easiest to do something like this:

<img src="http://example.com/image.png" onerror="alert('Image not found or protected');" />

It is possible to find out, of course, but that would require making an HTTP request, which can be expensive - especially if the remote host is slow or under load.

Here's how you do that in Ruby

class CheckImageHotlinkStatus
  require 'net/http'
  require 'uri'
  def self.call(image_url)
    uri = URI(image_url)
    req = Net::HTTP::Get.new(uri)
    req['Referer'] = 'http://your-site-here.com'
    response = Net::HTTP.start(uri.hostname, uri.port) do |http|
      http.request(req)
    end
    # Net::HTTPForbidden ...download & embed
    # Net::HTTPOK ...fine to hotlink
    # ...everything else 
    puts response.class
  end
end

You can't easily detect this per-URL with client-side JavaScript, but you can circumvent hotlinking protections entirely with hotlink.js.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top