php - 为什么从我的网络服务器提供的图像不缓存在客户端上?

标签 php apache caching

我将我所有的图片都存储在 webroot 之后(在 /var/www/ 之前),这意味着网络服务器无法为我的图片发回缓存 header 。我需要添加什么才能使用户的网络缓存工作?目前,每次都会被同一个浏览器击中。

我的 <img>我页面上的路径看起来像这样:

<img src="pic.php?u=1134&i=13513&s=0">

编辑:会不会是因为“pic.php?u=1134&i=13513&s=0”不是一个有效的文件名之类的?

// pic.php
<?php

    // open the file in a binary mode
    $user = $_GET['u'];
    $id = $_GET['i'];
    $s = $_GET['s'];

    if (!isset($user) && !isset($s) && $isset($id))
    {
        // display a lock!
        exit(0);
    }

    require_once("bootstrap_minimal.php"); //setup db connection, etc

    // does this image_id belong to the user?
    $stmt = $db->query('SELECT image_id, user_id, file_name, private FROM images WHERE image_id = ?', $id);
    $obj = $stmt->fetchObject();

    if (is_object($obj))
    {
        // is the picture is the users?
        if ($obj->user_id != $_SESSION['user_id'])
        {
            // is this a private picture?
            if ($obj->private == 1)
            {
                // check permissions...
                // display a lock in needed!
            }
        }
    }
    else
    {
        // display a error pic?!
        exit(0);
    }

    if ($s == 0)
    {
        $picture = $common->getImagePathThumb($obj->file_name);
    }
    else
    {
        $picture = $common->getImagePath($obj->file_name);
    }

    // send the right headers
    header("Content-Type: image/png");
    header("Content-Length: " . filesize($picture));

    $fp = fopen($picture, 'rb');

    // dump the picture and stop the script
    fpassthru($fp);
    exit;
?>

最佳答案

您需要添加如下内容:

$expiry = 3600*24*7; // A week
header('Expires: ' . gmdate('D, d M Y H:i:s' time() + $expiry) . ' GMT');
header('Cache-control: private, max-age=' . $expiry);

关于php - 为什么从我的网络服务器提供的图像不缓存在客户端上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/947638/

相关文章:

PHP 简单 XML 迭代器

python - Vagrant、WSGI、virtualenv 和 TypeError : 'module' object is not callable

java - Java 项目中的自动更新属性文件值

http - X-Cache header 说明

python - 将缓存 token 与 Spotipy for Spotify 一起使用时遇到问题?

php - 如何在 PHP 中获取有用的错误消息?

php - 使用 PHP 和多维数组将 MySQL 结果转换为 XML 格式

javascript - 使用 $.ajax 请求将数据发送到服务器

java - 2 种方式的 SSL 身份验证无法使用 Apache httpclient : JAVA

c++ - 使用redis做日志缓存 : Is it possible to create an eviction policy that evicts to PostgreSQL?