如何使用 PHP 让浏览器缓存图像? [英] How to get the browser to cache images, with PHP?

查看:36
本文介绍了如何使用 PHP 让浏览器缓存图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对如何缓存图像完全陌生.

I'm totally new to how to cache images.

我使用 PHP 输出图库中的所有图像,并希望已显示的图像由浏览器缓存,因此 PHP 脚本不必再次输出相同的图像.我想要的只是图像显示得更快.

I output all images in a gallery with PHP, and want the images already shown, to be cached by the browser, so the PHP script don't have to output the same image again. All I want is the images to show up faster.

调用图像时,我喜欢这样:

When calling an image I do like this:

<img src="showImage.php?id=601">

showImage.php 文件:

$id = (int) $_GET['id'];
$resultat = mysql_query("
    SELECT filename, id
    FROM Media 
    WHERE id = $id
");
$data = mysql_fetch_assoc($resultat);

...

//Only if the user are logged in
if(isset($_SESSION['user'])){
    header("Content-Type: image/jpeg");

    //$data['filename'] can be = dsSGKLMsgKkD3325J.jpg
    echo(file_get_contents("images/".$data['filename']."")); 
}

推荐答案

如果您在输出消息之前使用 php 检查用户是否已登录,那么您不希望浏览器缓存图像.

If you are using php to check if the user is logged in before outputting the message, then you don't want the browser to cache the image.

>

缓存的全部意义在于调用服务器一次,然后再也不调用它.如果浏览器缓存图像,它不会调用服务器并且您的脚本不会运行.相反,即使用户不再登录,浏览器也会从缓存中提取您的图像并显示它.这可能是一个非常大的安全漏洞.

The entire point of caching is to call the server once and then never call it again. If the browser caches the image, it won't call the server and your script won't run. Instead, the browser will pull your image from cache and display it, even if the user is no longer logged in. This could potentially be a very big security hole.

这篇关于如何使用 PHP 让浏览器缓存图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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