php 写出常用HTTP头
封面图
•
2026-01-06
•
PHP
218
0
0
0
在 PHP 中,你可以使用 `header()` 函数来设置 HTTP 响应头。以下是一些**常用的 HTTP 头字段**及其用途: --- ### ✅ **常用 HTTP 响应头(Response Headers)** | 头字段 | 说明 | 示例 | |--------|------|------| | `Content-Type` | 指定响应内容的 MIME 类型 | `header('Content-Type: text/html');` | | `Location` | 用于重定向(301, 302 等) | `header('Location: https://example.com');` | | `Cache-Control` | 控制缓存行为 | `header('Cache-Control: no-cache');` | | `Expires` | 设置过期时间(HTTP 1.0) | `header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');` | | `Last-Modified` | 表示资源最后修改时间 | `header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $file_mtime) . ' GMT');` | | `ETag` | 资源的唯一标识符(用于缓存验证) | `header('ETag: "abc123"');` | | `Set-Cookie` | 设置 Cookie | `header('Set-Cookie: user=John; path=/');` | | `Content-Length` | 响应体长度(通常由服务器自动处理) | `header('Content-Length: ' . strlen($content));` | | `Content-Encoding` | 压缩方式(如 gzip) | `header('Content-Encoding: gzip');` | | `Vary` | 用于缓存控制(根据请求头不同返回不同内容) | `header('Vary: Accept-Encoding');` | | `WWW-Authenticate` | 需要认证时返回 | `header('WWW-Authenticate: Basic realm="My Realm"');` | | `Access-Control-Allow-Origin` | 允许跨域访问 | `header('Access-Control-Allow-Origin: *');` | | `X-Content-Type-Options` | 防止 MIME 类型嗅探 | `header('X-Content-Type-Options: nosniff');` | | `X-Frame-Options` | 防止点击劫持 | `header('X-Frame-Options: DENY');` | | `X-XSS-Protection` | 防止 XSS 攻击 | `header('X-XSS-Protection: 1; mode=block');` | | `Strict-Transport-Security` | 强制 HTTPS | `header('Strict-Transport-Security: max-age=31536000');` | --- ### 🚫 注意事项 - `header()` 必须在任何输出(包括空格、换行)之前调用。 - 如果你已经发送了输出内容,再调用 `header()` 会失败并报错。 - 使用 `headers_sent()` 可以检查是否已经发送了 HTTP 头。 --- ### ✅ 示例代码 ```php <?php // 设置 Content-Type header('Content-Type: application/json'); // 设置重定向 header('Location: https://example.com'); // 设置缓存控制 header('Cache-Control: no-cache, no-store, must-revalidate'); // 设置跨域访问 header('Access-Control-Allow-Origin: *'); // 设置 Cookie header('Set-Cookie: user=John; path=/; HttpOnly'); ?> ``` --- 如果你有特定用途(比如 API 返回 JSON、文件下载、登录重定向等),可以告诉我,我可以提供更具体的示例。
上一篇:
apache+mysql+php实现最大负载的方法
下一篇:
php获取一个网页的内容
标题录入,一次不能超过6条
留言
评论