答案:PHP中header()函数必须在任何输出前调用,否则会触发“Headers already sent”错误。常见用途包括设置Content-Type、页面重定向、状态码、Cookie和文件下载,需注意调用时机与输出缓冲控制。

PHP中设置HTTP响应头信息,核心就是依赖
header()
header()
在PHP里,如果你想对客户端发出HTTP响应头,
header()
最常见的形式是这样:
header("Header-Name: Header-Value");比如,你想告诉浏览器你返回的是一个JSON格式的数据,而不是默认的HTML:
<?php
header("Content-Type: application/json; charset=utf-8");
echo json_encode(['message' => 'Hello, world!']);
exit;
?>这里有个非常关键的点,也是我个人在早期开发中经常犯错的地方:
header()
header()
立即学习“PHP免费学习笔记(深入)”;
除了
Content-Type
header()
页面重定向: 这是最常用的功能之一,强制浏览器跳转到另一个URL。
<?php
header("Location: https://www.example.com/new-page.php");
exit; // 重定向后立即终止脚本,防止后续代码执行
?>这里
exit;
设置HTTP状态码: 默认情况下,PHP会发送
200 OK
<?php
// 方法一:直接设置HTTP状态行
header("HTTP/1.0 404 Not Found");
// 方法二:使用http_response_code(),更现代也更推荐
http_response_code(404);
echo "<h1>404 - 页面未找到</h1>";
?>我个人更倾向于
http_response_code()
设置Cookie: 虽然有
setcookie()
Set-Cookie
<?php
header("Set-Cookie: username=john_doe; expires=" . gmdate("D, d M Y H:i:s T", time() + 3600) . "; path=/");
// 或者更推荐使用 setcookie() 函数
// setcookie("username", "john_doe", time() + 3600, "/");
?>文件下载: 当你想让浏览器下载文件而不是直接打开它时,
Content-Disposition
<?php
$filename = "document.pdf";
header("Content-Type: application/octet-stream"); // 或具体的文件MIME类型
header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
// header("Content-Length: " . filesize($filepath)); // 如果知道文件大小,加上这个会更好
readfile($filepath); // 输出文件内容
exit;
?>这里
application/octet-stream
header()
header()
说实话,
header()
这个错误通常发生在你的PHP脚本在调用
header()
以上就是php如何设置响应头信息?php header()函数设置HTTP头信息的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号