2

Suppose i have an image url :- example.com/myimg.png

I want to check whether it is included inside img src or someone directly opened it via browser.

What i need:- Check this image of GIPHY - https://media3.giphy.com/media/N8Lfh9gWcWYIU/giphy.gif

if you directly open it inside browser then it contains links at top and bottom of image but if you include this image inside img src then it only displays an image.

I tried below code but it is not a reliable solution:-

$ref = isset($_SERVER['HTTP_REFERER'])? $_SERVER['HTTP_REFERER']: "";
if ($ref != "")
{
    header( 'Content-Type: image/jpeg' );
    readfile( 'my-image.jpg' );
}
else
{
  <img src="my-image.jpg">
  <a href="#">My Link</a>
}
Satinder Singh
  • 29
  • 1
  • 1
  • 10
  • 4
    That's because the above giphy-link isn't actually a link to an image. It's a link to a page. The real image link for the above is https://i.giphy.com/media/N8Lfh9gWcWYIU/giphy.webp, which you can access directly. – M. Eriksson May 14 '19 at 05:55
  • Also, posting a link to an example doesn't really answer _"Why I need this"_. It's rather _"What I want"_ – M. Eriksson May 14 '19 at 06:06
  • 1
    @MagnusEriksson I know that i.giphy.com/media/N8Lfh9gWcWYIU/giphy.webp is real image url but i can also pass https://media3.giphy.com/media/N8Lfh9gWcWYIU/giphy.gif inside img src attribute and it works without any issue - how it works if it is not an image? – Satinder Singh May 14 '19 at 08:39
  • @MagnusEriksson can you explain that further? When using `wget`, only the image is downloaded, no markup – Nico Haase May 14 '19 at 08:43
  • @Magnus Eriksson is incorrect. The server *may* reply with an image or with a 302 redirect depending on `Accept` request header. – Sanya_Zol Nov 28 '19 at 23:31

1 Answers1

2

TL;DR giphy analyzes Accept HTTP header and also uses Age: header value greater than Cache-Control: max-age= value

When your browser loads an image in <img> tag, it sends specific Accept header. Firefox 71.0b12, for example, will use

Accept: image/webp,*/*

But if you open this URL in browser, even with same Referer header, the browser will send another request with header

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

But there is more. Due to caching browser will not send another request.

To avoid this, giphy will reply with following headers:

Last-Modified: ...
Etag: "..."
Content-Type: image/gif
Cache-Control: max-age=86400
Age: 99360

(other headers omitted, order not preserved)

As you can see, Age is greater than max-age, so it is considered "stale" by the browser instantly, forcing another request when opening image directly.

Note that this method may not work in all browsers.

Sanya_Zol
  • 488
  • 3
  • 9