PHP Header 函数基础与常用设置
在 PHP 开发过程中,经常需要利用 header 函数来添加特定的标记或元数据。
该函数主要用于向浏览器客户端发送原始的 HTTP 响应报头。
以下是常用的 header 设置列表及其应用场景:
header('HTTP/1.1 200 OK'); // 表示正常访问成功 header('HTTP/1.1 404 Not Found'); // 通知浏览器请求的页面不存在 header('HTTP/1.1 301 Moved Permanently'); // 设置永久重定向,状态码为 301 header('Location: http://www.ithhc.cn/'); // 将请求跳转到一个新的 URL 地址 header('Refresh: 10; url=http://www.ithhc.cn/'); // 实现延迟跳转,即等待指定秒数后自动跳转 header('X-Powered-By: PHP/6.0.0'); // 修改服务器返回的 X-Powered-By 标识信息 header('Content-language: en'); // 指定文档的语言环境 header('Content-Length: 1234'); // 明确设置返回内容的字节长度 header('Last-Modified: '.gmdate('D, d M Y H:i:s', $time).' GMT'); // 告知浏览器资源最后一次修改的时间 header('HTTP/1.1 304 Not Modified'); // 告知浏览器本地缓存有效,无需重新获取内容
内容类型
header('Content-Type: text/html; charset=utf-8'); // 指定网页编码格式 header('Content-Type: text/plain'); // 声明内容为纯文本格式 header('Content-Type: image/jpeg'); // 声明内容为 JPG 或 JPEG 图片 header('Content-Type: application/zip'); // 声明内容为 ZIP 压缩文件 header('Content-Type: application/pdf'); // 声明内容为 PDF 文档 header('Content-Type: audio/mpeg'); // 声明内容为 MPEG 音频文件 header('Content-type: text/css'); // 声明内容为 CSS 样式表 header('Content-type: text/javascript'); // 声明内容为 JavaScript 脚本 header('Content-type: application/json'); // 声明内容为 JSON 数据 header('Content-type: application/pdf'); // 再次声明 PDF 文件类型 header('Content-type: text/xml'); // 声明内容为 XML 格式文件 header('Content-Type: application/x-shockw**e-flash'); // 声明内容为 Flash 动画
声明一个下载的文件
header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="ITblog.zip"'); header('Content-Transfer-Encoding: binary'); readfile('test.zip');
对当前文档禁用缓存
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
显示一个需要验证的登陆对话框
header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Basic realm="Top Secret"');
声明一个需要下载的 xls 文件
header('Content-Disposition: attachment; filename=ithhc.xlsx'); header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Length: '.filesize('./test.xls')); header('Content-Transfer-Encoding: binary'); header('Cache-Control: must-revalidate'); header('Pragma: public'); readfile('./test.xls');
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。