答案:PHP的header()函数用于设置HTTP头,必须在任何输出前调用,否则会触发“Headers already sent”错误。它可控制内容类型、重定向、缓存、Cookie及安全策略,是实现文件下载、页面跳转和性能优化的关键工具。正确使用需遵循输出缓冲、状态码指定、exit终止脚本等最佳实践,避免常见陷阱。

PHP通过其内置的
header()
使用
header()
header()
基本用法:
header("Header-Name: Header-Value", [replace], [http_response_code]);Header-Name: Header-Value
replace
true
true
false
Set-Cookie
http_response_code
200
301
404
示例:
立即学习“PHP免费学习笔记(深入)”;
<?php
// 设置内容类型为JSON
header("Content-Type: application/json; charset=UTF-8");
// 设置页面重定向
header("Location: /new-page.php", true, 302);
exit(); // 重定向后通常需要停止脚本执行
// 设置缓存控制,让浏览器在60秒内缓存响应
header("Cache-Control: max-age=60, public");
// 发送文件下载
header("Content-Description: File Transfer");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"document.pdf\"");
header("Content-Length: " . filesize("path/to/document.pdf"));
readfile("path/to/document.pdf");
exit();
// 设置一个Cookie
header("Set-Cookie: user_id=123; expires=" . gmdate("D, d M Y H:i:s T", time() + 3600) . "; path=/; httponly");
// 设置一个自定义头
header("X-Custom-Header: My-Value");
// 设置HTTP状态码,例如未授权
header("HTTP/1.0 401 Unauthorized");
?>在我看来,HTTP头信息是Web通信的“幕后语言”,它虽然不直接呈现在用户眼前,却深刻地决定了用户如何与你的应用互动,甚至影响着应用的性能和安全性。想象一下,如果Web服务器和浏览器之间没有这些“约定”,那将是一片混乱。
首先,它控制着内容的呈现方式。
Content-Type
Content-Type: application/json
其次,HTTP头是性能优化的核心。
Cache-Control
Expires
ETag
再者,安全策略的实施也离不开它。
X-Frame-Options
Content-Security-Policy
Strict-Transport-Security
最后,它还是实现特定功能的关键,比如文件下载 (
Content-Disposition
Location
header()
header()
在使用
header()
常见陷阱:
“Headers already sent”错误: 这是最让人头疼的问题。它的根本原因在于,
header()
header()
检查文件开头: 确保PHP文件的开头没有任何空格或BOM。使用一个好的IDE通常可以避免BOM问题。
输出缓冲: 这是最可靠的解决方案。在脚本的最开始调用
ob_start()
ob_end_flush()
header()
<?php
ob_start(); // 开启输出缓冲
// ... 你的代码,可能包含一些输出 ...
echo "一些内容";
// 现在可以安全地设置头信息了
header("Location: /dashboard.php");
exit(); // 记得退出
?>逻辑前置: 尽量将所有
header()
echo
不正确的HTTP状态码: 仅仅设置
Location
301
302
303
307
200 OK
多重Set-Cookie
header("Set-Cookie: ...")header()
replace
true
Set-Cookie
header("Set-Cookie: ...", false)setcookie()
最佳实践:
header()
ob_start()
X-Frame-Options
X-Content-Type-Options
Content-Security-Policy
Content-Type
application/json
text/html
exit()
die()
Location
exit()
die()
header()
文件下载和页面重定向是Web应用中最常用的两个功能,而
header()
实现文件下载,你需要告诉浏览器:
以下是一个典型的文件下载PHP脚本示例:
<?php
// 假设要下载的文件路径和文件名
$filePath = 'path/to/your/document.pdf'; // 替换为你的实际文件路径
$fileName = 'MyReport_2023.pdf'; // 浏览器建议保存的文件名
if (!file_exists($filePath)) {
header("HTTP/1.0 404 Not Found");
echo "文件未找到。";
exit();
}
// 1. 告诉浏览器这是一个文件传输
header("Content-Description: File Transfer");
// 2. 设置内容类型
// 对于未知类型或二进制文件,通常使用 application/octet-stream
// 对于已知类型,可以使用更具体的MIME类型,如 application/pdf, image/jpeg 等
header("Content-Type: application/octet-stream");
// 3. 告诉浏览器以附件形式下载,并指定文件名
header("Content-Disposition: attachment; filename=\"" . basename($fileName) . "\"");
// 4. 禁止缓存,确保每次都下载最新文件
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
// 5. 设置文件大小,有助于浏览器显示下载进度
header("Content-Length: " . filesize($filePath));
// 6. 清除任何可能存在的输出缓冲,防止内容损坏
ob_clean();
flush();
// 7. 读取文件并输出到浏览器
readfile($filePath);
exit();
?>关键点:
Content-Disposition: attachment; filename="..."
filename
Content-Type: application/octet-stream
application/pdf
Content-Length
readfile()
ob_clean()
flush()
页面重定向是告诉浏览器去访问另一个URL。这在用户登录后跳转到仪表盘、处理表单提交后跳转到结果页,或者旧URL失效时跳转到新URL等场景中非常常见。
<?php
// 假设用户成功登录,需要重定向到仪表盘
$redirectUrl = "/dashboard.php";
// 1. 设置Location头,指定重定向目标URL
// 注意:URL必须是绝对路径或相对于当前域的根路径
header("Location: " . $redirectUrl);
// 2. 设置HTTP状态码
// 301 Moved Permanently: 永久重定向,搜索引擎会更新索引
// 302 Found (或 303 See Other, 307 Temporary Redirect): 临时重定向
// 对于大多数临时跳转,302或303是合适的。
header("HTTP/1.1 302 Found"); // 或者 header("Location: " . $redirectUrl, true, 302);
// 3. 极其重要:终止脚本执行
// 否则,服务器会继续处理并发送当前页面的剩余内容,可能导致意外行为或安全问题。
exit();
?>关键点:
Location: /new-page.php
HTTP/1.1 302 Found
301 Moved Permanently
301
302
303 See Other
307 Temporary Redirect
exit()
Location
缓存是提升Web应用性能的“魔法”,它能显著减少服务器负载,加快页面加载速度,改善用户体验。而HTTP头,正是控制浏览器和中间缓存服务器如何进行缓存的核心机制。
缓存策略通常分为两种:强缓存和协商缓存。
强缓存策略下,浏览器在一定时间内不会向服务器发送请求,直接使用本地缓存的资源。这通过以下HTTP头实现:
Cache-Control
public
private
no-cache
no-store
max-age=<seconds>
s-maxage=<seconds>
max-age
must-revalidate
proxy-revalidate
must-revalidate
示例:
立即学习“PHP免费学习笔记(深入)”;
// 资源在600秒内有效,可以被公共缓存
header("Cache-Control: max-age=600, public");
// 不缓存敏感数据
header("Cache-Control: no-store");Expires
Cache-Control: max-age
max-age
示例:
立即学习“PHP免费学习笔记(深入)”;
// 资源在未来一小时后过期
header("Expires: " . gmdate("D, d M Y H:i:s T", time() + 3600));当强缓存失效(例如
max-age
no-cache
304 Not Modified
ETag
If-None-Match
ETag
ETag
304
示例(服务器端):
$content = file_get_contents('path/to/resource.js');
$etag = md5($content); // 简单示例,实际应用中可能更复杂
header("ETag: \"{$etag}\"");
header("Cache-Control: no-cache"); // 配合ETag,每次都协商
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && trim($_SERVER['HTTP_IF_NONE_MATCH']) == "\"{$etag}\"") {
header("HTTP/1.1 304 Not Modified");
exit();
}
echo $content;Last-Modified
If-Modified-Since
304
示例(服务器端):
$lastModifiedTime = filemtime('path/to/resource.css'); // 获取文件最后修改时间
$lastModifiedGmt = gmdate("D, d M Y H:i:s T", $lastModifiedTime);
header("Last-Modified: " . $lastModifiedGmt);
header("Cache-Control: no-cache"); // 配合Last-Modified,每次都协商
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $lastModifiedTime) {
header("HTTP/1.1 304 Not Modified");
exit();
}
echo file_get_contents('path/to/resource.css');总结与实践建议:
Cache-Control: max-age
ETag
Last-Modified
max-age
ETag
Last-Modified
no-cache
style.v123.css
s-maxage
public
在我看来,缓存策略的配置,就像是给你的Web应用做“交通管制”。做得好,资源流转顺畅,用户体验极佳;做得不好,要么用户总在等待,要么看到过时信息。这需要细致的分析和测试,才能找到最佳平衡点。
以上就是PHP如何设置HTTP头信息_PHP使用header函数设置HTTP头信息详解的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号