PHP header 函数
最后修改于 2025 年 4 月 4 日
PHP header 函数将原始 HTTP 标头发送给客户端。它必须在将任何实际输出发送到浏览器之前调用。
基本定义
header 在任何内容之前将 HTTP 标头发送到浏览器。标头控制缓存、重定向、内容类型等。
语法:header(string $header, bool $replace = true, int $response_code = 0): void。该函数必须在生成任何输出之前调用。
基本重定向示例
此示例演示了使用 header 函数的简单页面重定向。
redirect.php
<?php
declare(strict_types=1);
header("Location: https://www.example.com/newpage.php");
exit;
这会将 302 重定向标头发送到浏览器。exit 语句阻止进一步的脚本执行。始终在 Location 标头之后包含 exit。
设置内容类型
这显示了如何为各种文件格式设置不同的内容类型。
content_type.php
<?php
declare(strict_types=1);
// For JSON response
header('Content-Type: application/json');
// For plain text
// header('Content-Type: text/plain');
// For XML
// header('Content-Type: application/xml');
echo json_encode(['status' => 'success', 'message' => 'Data loaded']);
设置适当的内容类型可确保浏览器正确解释响应。不同的 API 需要特定的内容类型才能正常运行。
强制文件下载
此示例强制浏览器下载文件而不是显示它。
force_download.php
<?php
declare(strict_types=1);
$filename = 'report.pdf';
$filepath = '/path/to/files/' . $filename;
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
exit;
这会发送标头以触发下载对话框。Content-Disposition 标头指定文件名。对于大文件,始终包含 Content-Length。
设置缓存控制
这演示了如何使用 HTTP 标头控制浏览器缓存。
cache_control.php
<?php
declare(strict_types=1);
// Prevent caching
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
// Or set future expiration
// header("Cache-Control: public, max-age=86400");
// header("Expires: " . gmdate('D, d M Y H:i:s', time() + 86400) . ' GMT');
echo "This content has specific caching rules applied";
缓存标头控制浏览器如何存储响应。不同的场景需要不同的缓存策略以获得最佳性能。
设置 HTTP 状态码
此示例显示了如何发送不同的 HTTP 状态码。
status_codes.php
<?php
declare(strict_types=1);
// 404 Not Found
header("HTTP/1.0 404 Not Found");
// 500 Internal Server Error
// header("HTTP/1.0 500 Internal Server Error");
// 301 Moved Permanently
// header("HTTP/1.1 301 Moved Permanently");
// header("Location: /new-url.php");
echo "Error: Page not found";
exit;
HTTP 状态码将请求结果传达给客户端。适当的状态码有助于 SEO 和 API 响应处理。
最佳实践
- 输出缓冲:使用 ob_start() 防止标头错误
- 提前执行:在任何输出之前调用 header()
- 重定向后退出:始终在 Location 标头后退出
- 内容类型:始终设置适当的内容类型
- 状态码:使用正确的 HTTP 状态码
来源
本教程介绍了 PHP header 函数,并提供了在各种情况下进行 HTTP 标头操作的实用示例。
作者
列出 所有 PHP 网络函数。