在提供内容时在标题中添加“EXPIRE”标记

时间:2011-06-28 03:39:17

标签: php http-headers

在标题中添加“EXPIRE”标记会强制浏览器缓存内容直到时间到期为止? 如何在PHP中提供静态图像/ css / js时这样做?

2 个答案:

答案 0 :(得分:1)

您可以使用header和gmdate函数:

// Actualy date in GTM 0
header('Date: '.gmdate('D, d M Y H:i:s \G\M\T', time())); 

// Las modify date (now, for example)
header('Last-Modified: '.gmdate('D, d M Y H:i:s \G\M\T', time())); 

// The expire time (one hour in the future) <-- sorry my english!!!
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 3600)); 

始终确保在发送数据之前发送标头,例如:

// GOOD!
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 3600));
echo "content";

// BAD!
echo "some content";
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 3600));

如果您需要在发送标题之前生成内容,则可以使用ob函数:

ob_start();

echo "content";
echo "more content";


header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 3600));
ob_end_flush();

答案 1 :(得分:0)

对于静态内容,请使用Web服务器配置。对于apache,它是.htaccess,因为它是web.config。