PHP 怎么PHP Pragma

wen PHP项目 2

本文目录导读:

PHP 怎么PHP Pragma

  1. 设置 Pragma 头部
  2. 实际应用示例
  3. 与 Cache-Control 的关系
  4. 完整示例:动态内容防止缓存
  5. 常见问题解决
  6. 现代替代方案

在 PHP 中,Pragma 是一个 HTTP 头字段,主要用于控制缓存行为,虽然它最初在 HTTP/1.0 中定义,但在 PHP 中仍然可以通过 header() 函数来设置,以下是几种常见的用法:

设置 Pragma 头部

基本语法

header('Pragma: value');

常见值

禁用缓存(最常用)

header('Pragma: no-cache');

设置缓存

header('Pragma: cache');

实际应用示例

完整禁用缓存示例

<?php
// 禁用缓存
header('Pragma: no-cache');
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
echo "This page should not be cached";
?>

控制特定资源的缓存

<?php
// 允许缓存但需要验证
header('Pragma: no-cache');
header('Cache-Control: private, max-age=0, must-revalidate');
// 或者允许缓存
header('Pragma: public');
header('Cache-Control: public, max-age=3600'); // 缓存1小时
?>

与 Cache-Control 的关系

现代浏览器更推荐使用 Cache-ControlPragma 主要是为了向后兼容 HTTP/1.0:

<?php
header('Pragma: no-cache');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Expires: 0');
?>

完整示例:动态内容防止缓存

<?php
// 防止浏览器缓存动态生成的页面
function preventCaching() {
    header('Pragma: no-cache');
    header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
    header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
}
// 使用
preventCaching();
echo "Dynamic content generated at: " . date('Y-m-d H:i:s');
?>

常见问题解决

多头部设置

// 如果多次调用 header,确保不冲突
header_remove('Pragma'); // 移除已设置的 Pragma
header('Pragma: no-cache');

检查是否已发送头部

if (!headers_sent()) {
    header('Pragma: no-cache');
}

现代替代方案

对于现代应用,建议使用:

// 更全面的缓存控制
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache'); // 向后兼容

注意:

  • Pragma 在 HTTP/1.1 中已被 Cache-Control 替代,但为了兼容性,通常两者都设置
  • 所有 header() 调用必须在任何输出之前执行
  • 某些代理服务器和旧浏览器仍然依赖 Pragma 头部

这样,你就能在 PHP 中正确使用 Pragma 头部来控制缓存行为了。

抱歉,评论功能暂时关闭!