1. PHP中header()函数基础解析
header()函数是PHP中用于发送原始HTTP头信息的内置函数,它允许开发者直接操作HTTP响应头,这在Web开发中具有举足轻重的作用。这个函数看似简单,但实际应用中却藏着不少门道。我们先来看它的基本语法:
php复制header(string $header, bool $replace = true, int $response_code = null): void
第一个参数是头信息字符串,第二个参数控制是否替换之前相同类型的头信息(默认为true),第三个参数可以强制指定HTTP响应码。需要注意的是,header()必须在任何实际输出之前调用,否则会触发"Headers already sent"错误——这是新手最容易踩的坑。
重要提示:使用header()函数前确保没有输出任何内容(包括空格和BOM头),建议在PHP文件开头加上
ob_start()启用输出缓冲。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 七种核心应用场景详解
2.1 页面重定向
最经典的用法莫过于实现页面跳转:
php复制header("Location: https://www.example.com/newpage.php");
exit; // 必须跟exit或die防止后续代码执行
这里有几个关键细节:
- Location后的URL可以是绝对路径或相对路径
- 现代实践中建议使用完整的绝对URL
- 必须跟exit/die,否则后续代码仍会执行
- 默认返回302临时重定向,如需永久重定向需指定状态码:
php复制header("Location: /newpage.php", true, 301);
2.2 控制缓存行为
通过设置Cache-Control和Expires头可以有效控制浏览器缓存:
php复制// 禁止缓存当前页面
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache"); // HTTP 1.0
header("Expires: 0"); // 代理服务器缓存
对于需要缓存的静态资源,可以这样设置:
php复制$seconds_to_cache = 86400; // 1天
header("Cache-Control: public, max-age=".$seconds_to_cache);
header('Expires: '.gmdate('D, d M Y H:i:s', time()+$seconds_to_cache).' GMT');
2.3 强制文件下载
实现文件下载功能时,通过设置Content-Disposition可以让浏览器弹出下载对话框:
php复制header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
