欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php header 使用详解

程序员文章站 2022-05-03 19:58:50
...
  1. Header("Location: http://www.php.net");
  2. ?>
复制代码

强制用户每次访问这个页面时获取最新资料,而不是使用存在客户端的缓存。

  1. //告诉浏览器此页面的过期时间(用格林威治时间表示),只要是已经过去的日期即可。
  2. header("Expires: Mon, 26 Jul 1970 05:00:00 GMT");
  3. //告诉浏览器此页面的最后更新日期(用格林威治时间表示)也就是当天,目的就是强迫浏览器获取最新资料
  4. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
  5. //告诉客户端浏览器不使用缓存
  6. header("Cache-Control: no-cache, must-revalidate");
  7. //参数(与以前的服务器兼容),即兼容HTTP1.0协议
  8. header("Pragma: no-cache");
  9. //输出MIME类型
  10. header("Content-type: application/file");
  11. //文件长度
  12. header("Content-Length: 227685");
  13. //接受的范围单位
  14. header("Accept-Ranges: bytes");
  15. //缺省时文件保存对话框中的文件名称
  16. header("Content-Disposition: attachment; filename=$filename");
  17. ?>
复制代码

输出状态值到浏览器,主要用于访问权限控制

  1. header('HTTP/1.1 401 Unauthorized');
  2. header('status: 401 Unauthorized');
  3. ?>
复制代码

比如要限制一个用户不能访问该页,则可设置状态为404,如下所示,这样浏览器就显示为即该页不存在

  1. header('HTTP/1.1 404 Not Found');
  2. header("status: 404 Not Found");
  3. ?>
复制代码

注意: 传统的标头一定包含下面三种标头之一,并只能出现一次。 Content-Type: xxxx/yyyy Location: xxxx:yyyy/zzzz Status: nnn xxxxxx 在新的多型标头规格 (Multipart MIME) 方可以出现二次以上。 以上就是有关php header头信息的内容介绍,更多内容可以参考:php 文件头部(header)信息详解

举一些具体的例子。

例1: 本例使浏览器重定向到 PHP 的官方网站。

  1. Header("Location: http://www.php.net"); exit;
复制代码

例2: 要使用者每次都能得到最新的资料,而不是 Proxy 或 cache 中的资料,可以使用下列的标头

  1. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  2. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT"); header("Cache-Control: no-cache, must-revalidate");
  3. header("Pragma: no-cache");
复制代码

例3: 让使用者的浏览器出现找不到档案的信息。

  1. header("Status: 404 Not Found");
复制代码

例4:让使用者下载档案。

  1. header("Content-type: application/x-gzip");
  2. header("Content-Disposition: attachment; filename=文件名");
  3. header("Content-Description: PHP3 Generated Data");
复制代码

说明: 不管页面有多少header,它会执行最后一个,不过是有条件的,例如:

  1. header('Location:http://bbs.it-home.org');
  2. header('Location:http://www.g.cn');
  3. header('Location:http://www.baidu.com');
  4. //跳到百度
  5. header('Location:http://bbs.it-home.org');echo '程序员之家';
  6. header('Location:http://www.g.cn');
  7. header('Location:http://www.baidu.com');
  8. //跳到google
复制代码