为什么从我的Web服务器提供的图像不会缓存在客户端上?

时间:2009-06-03 22:37:39

标签: php apache caching

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

我的网页上的<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;
?>

5 个答案:

答案 0 :(得分:5)

您需要添加以下内容:

$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);

答案 1 :(得分:2)

Apache默认只缓存静态文件。您需要通过header()函数发送缓存控制标头。 This article有很多关于该主题的信息。

或者,您可以使用PHP文件重定向到图像的实际位置。 (如果你对标题一无所知,这可能是最简单的方法。)

答案 2 :(得分:1)

您可以尝试:

header("Cache-Control: max-age=3600");

那应该在文件上发送一小时的缓存超时。

答案 3 :(得分:0)

在您的情况下,我要做的是使用.php文件流式传输图像的字节。不要直接链接到图像;相反,链接到一个PHP文件: - 输出缓存头 - 从webroot后面读取磁盘上的文件 - 将图像位向下发送

答案 4 :(得分:0)

简单回答:您没有告诉用户的浏览器缓存它

相关问题