简体   繁体   English

PHP - 检查图像是否加载到 img src 中或直接在浏览器中加载?

[英]PHP - Check if an image loaded inside img src or directly inside browser?

Suppose i have an image url :- example.com/myimg.png假设我有一个图片网址:- example.com/myimg.png

I want to check whether it is included inside img src or someone directly opened it via browser.我想检查它是否包含在 img src 中或有人通过浏览器直接打开它。

What i need:- Check this image of GIPHY - https://media3.giphy.com/media/N8Lfh9gWcWYIU/giphy.gif我需要什么:-检查 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.如果您直接在浏览器中打开它,那么它会在图像的顶部和底部包含链接,但是如果您将此图像包含在 img src 中,那么它只会显示一个图像。

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>
}

TL;DR giphy analyzes Accept HTTP header and also uses Age: header value greater than Cache-Control: max-age= value TL;DR giphy 分析Accept HTTP header 并使用Age: header value 大于Cache-Control: max-age= value

When your browser loads an image in <img> tag, it sends specific Accept header.当您的浏览器在<img>标签中加载图像时,它会发送特定的Accept标头。 Firefox 71.0b12, for example, will use例如,Firefox 71.0b12 将使用

Accept: image/webp,*/*

But if you open this URL in browser, even with same Referer header, the browser will send another request with header但是如果你在浏览器中打开这个 URL,即使使用相同的Referer header,浏览器也会发送另一个带有 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:为避免这种情况,giphy 将回复以下标题:

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.如您所见, Age大于max-age ,因此浏览器立即将其视为“陈旧”,直接打开图像时强制另一个请求。

Note that this method may not work in all browsers.请注意,此方法可能不适用于所有浏览器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM