如何通过PHP脚本加载图像缓存 [英] How are images cached when loaded via php script

查看:85
本文介绍了如何通过PHP脚本加载图像缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP脚本充当随机图像生成器。该脚本在数据库中查询用户的图像,并随机返回路径。一旦选择了路径,以下是负责返回图像的代码部分。

I have a php script acting as a random image generator. The script queries the database for the user's images, and returns the path to one, at random. Here is the portion of the code responsible for returning the image, once the path has been chosen.

header('Content-Transfer-Encoding: binary');
header('Content-Type: image/jpeg');
header('Content-Length: ' . filesize($path));
echo file_get_contents($path);

我正在从客户端调用它,如此

I am calling it from the client like so

image.src = "/database/getRandomImage.php";

每次刷新页面时,我都会随机获得一个新图像。但是,如果我为并排图像多次调用 getRandomImage.php ,它们将是相同的图像。如果我像这样添加随机属性

Every time I refresh the page I get a new image at random. However, if I call getRandomImage.php multiple times for side by side images, they will all be the same image. If I add a random property to the call like so

image.src = "/database/getRandomImage.php?path=" + Math.random() * 100;

图片随机。我认为这意味着浏览器根据我传递的随机属性缓存它们。问题是这个属性与实际图像无关。两个不同的图像可能会被缓存为同一图像,并且可能无法从缓存中检索到相同的图像。有没有办法让 getRandomImage.php 通知浏览器它发回的图片?

The pictures become random. I take this to mean that the browser is caching them based on the random property I passed. The problem is this property has nothing to do with the actual image. Two different images might get cached as the same image, and the same image might not be retrieved from the cache. Is there any way for getRandomImage.php to inform the browser about the picture it is sending back?

推荐答案

为什么不让 getRandomImage 成为PHP函数,它返回图像的路径。您可以使用已填写的随机图像路径渲染页面。

Why not have getRandomImage be a PHP function, which returns a path to the image. You can render the page out with the random image paths already filled in.

<img src="<? echo getRandomImage() ?>">

然后你可以使用真正的缓存标题实际提供你的图像,你的带宽也不会受到如此严重的打击。

Then you can actually serve your images with real cache headers, and your bandwidth wont be getting hammered so hard.

在页面渲染时在服务器端执行此操作,而不是在之后。之后做更多的工作,正如你所发现的那样,也更复杂。

Do this on the server side while the page is rendering, not after. Doing it after is more work and, as you are finding out, is more complicated too.

这篇关于如何通过PHP脚本加载图像缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆