php_ref_http
PHP HTTP 函数
Section titled “PHP HTTP 函数”PHP HTTP 简介
Section titled “PHP HTTP 简介”PHP 提供了函数来直接与 HTTP 协议交互,主要用于操作从服务器发送到客户端(浏览器)的 HTTP 头部(headers)。这些函数允许你在发送任何页面内容(输出)之前控制诸如 cookie、缓存、内容类型、状态码和重定向等方面。
重要提示:修改 HTTP 头部(如 header()、setcookie()、session_start())的函数必须在向浏览器发送任何输出之前调用(包括 HTML、<?php 之前的空格,或 echo / print 语句)。否则将导致“Headers already sent”(头部已发送)警告或错误。
此处讨论的核心 HTTP 函数内置于 PHP 中,无需单独安装。
常用 HTTP 函数
Section titled “常用 HTTP 函数”| 函数 | 描述 |
|---|---|
header() | 发送原始 HTTP 头部字符串。用于重定向、设置内容类型、缓存指令、安全头部等。 |
headers_list() | 返回一个数字索引数组,包含计划发送(或已发送)的头部列表。 |
headers_sent() | 检查头部是否已发送,以及在何处发送。对于调试“Headers already sent”问题很有用。 |
setcookie() | 发送 Set-Cookie HTTP 头部,用于在客户端浏览器上创建或修改 cookie。 |
setrawcookie() | 类似于 setcookie(),但发送的 cookie 值未经 URL 编码。 |
http_response_code() | 获取或设置 HTTP 响应状态码(例如 200、404、500)。 |
设置内容类型:
<?php// Tell the browser to expect JSON dataheader('Content-Type: application/json');
echo json_encode(['status' => 'success', 'data' => [1, 2, 3]]);?>执行重定向:
<?php// Redirect to another page (common practice)header('Location: /new-page.php');exit; // Important: Stop script execution after sending redirect header?>设置 Cookie:
<?php$cookie_name = "user_preference";$cookie_value = "dark_theme";$expiry = time() + (86400 * 30); // Expires in 30 days (86400 seconds/day)$path = "/"; // Available for the entire domain
setcookie($cookie_name, $cookie_value, $expiry, $path);
// Rest of the page content...echo "Cookie '{$cookie_name}' has been set.";?>设置响应状态码:
<?php// Indicate a resource was not foundhttp_response_code(404);
echo "Error 404: Page Not Found";?>header() 函数对于设置 HTTP 安全头部至关重要,这有助于保护你的应用程序和用户免受各种攻击。常见示例包括:
Content-Security-Policy(CSP):通过指定允许的内容来源来缓解 XSS 攻击。Strict-Transport-Security(HSTS):强制使用 HTTPS 连接。X-Frame-Options:通过控制页面是否可以在框架中嵌入来防止点击劫持。X-Content-Type-Options:防止 MIME-sniffing 攻击。Referrer-Policy:控制发送多少 referrer 信息。
设置基本 CSP 头部的示例:
<?phpheader("Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com;");// ... rest of your page ...?>现代实践:PSR-7
Section titled “现代实践:PSR-7”虽然这些核心函数是基础,但现代 PHP 框架通常使用 PSR-7 (HTTP Message Interfaces) 来抽象 HTTP 交互。PSR-7 定义了 HTTP 请求和响应对象的标准接口,使得处理 HTTP 时代码更加结构化、可测试和可互操作。
框架通常提供 Request 和 Response 对象来管理头部、cookie、状态码和主体,这通常对应用程序开发者隐藏了对 header() 或 setcookie() 等函数的直接使用。
进一步阅读:
Section titled “进一步阅读:”- PHP 输出控制函数(与“Headers already sent”相关)
header()函数setcookie()函数http_response_code()函数- MDN Web 文档:HTTP 头部
- OWASP 安全头部项目
- PSR-7:HTTP 消息接口