当前位置:首页 > PHP教程 > php函数 > 列表

php header函数的详解

发布:smiling 来源: PHP粉丝网  添加日期:2014-09-14 21:07:26 浏览: 评论:0 

header函数在php中是发前一些头部信息的,如果我们可以直接使用它来做301跳转等,下面我来总结关于header函数用法与一些常用见问题解决方法。

发送一个原始 HTTP 标头[Http Header]到客户端,标头 (header) 是服务器以 HTTP 协义传 HTML 资料到浏览器前所送出的字串,在标头与 HTML 文件之间尚需空一行分隔

例1,代码如下:

  1. <?PHP 
  2. Header(“Location: http://www.phpfensi.com”;); 
  3. exit//在每个重定向之后都必须加上“exit”,避免发生错误后,继续执行。 
  4. ?> 

禁止页面在IE中缓存,代码如下:

  1. <?PHP 
  2. header( ‘Expires: Mon, 26 Jul 1997 05:00:00 GMT’ ); 
  3. header( ‘Last-Modified: ‘ . gmdate( ‘D, d M Y H:i:s’ ) . ‘ GMT’ ); 
  4. header( ‘Cache-Control: no-store, no-cache, must-revalidate’ ); 
  5. header( ‘Cache-Control: post-check=0, pre-check=0′, false ); 
  6. header( ‘Pragma: no-cache’ ); //兼容http1.0和https 
  7. ?> 
  8. //CacheControl = no-cache 
  9. //Pragma=no-cache 
  10. //Expires = -1 

实现文件下载,代码如下:

  1. header('Content-Type: application/octet-stream');//设置内容类型 
  2. header('Content-Disposition: attachment; filename="example.zip"'); //设置MIME用户作为附件下载 如果将attachment换成inline意思为在线打开 
  3. header('Content-Transfer-Encoding: binary');//设置传输方式 
  4. header('Content-Length: '.filesize('example.zip'));//设置内容长度 
  5. // load the file to send: 
  6. readfile('example.zip');//读取需要下载的文件 

php的函数header()可以向浏览器发送Status标头,代码如下:

header(”Status: 404 Not Found”)。

但是我发现实际上浏览器返回的响应却是如下代码:

  1. // ok 
  2. header(‘HTTP/1.1 200 OK’); 
  3. //设置一个404头: 
  4. header(‘HTTP/1.1 404 Not Found’); 
  5. //设置地址被永久的重定向 
  6. header(‘HTTP/1.1 301 Moved Permanently’); 
  7. HTTP/1.x 200 OK 
  8. Date: Thu, 03 Aug 2006 07:49:11 GMT 
  9. Server: Apache/2.0.55 (Win32) PHP/5.0.5 
  10. X-Powered-By: PHP/5.0.5 
  11. Status: 404 Not Found 
  12. //开源软件:phpfensi.com 
  13. Content-Length: 0 
  14. Keep-Alive: timeout=15, max=98 
  15. Connection: Keep-Alive 
  16. Content-Type: text/html 

注意事项有以下几点:

•Location和":"之间不能有空格,否则会出现错误(注释,我刚测试了,在我本地环境下,没有跳转页面,但是也没有报错,不清楚什么原因);

•在用header前不能有任何的输出(注释,这点大家都知道的,如果header之前有任何的输出,包括空白,就会出现header already sent by xxx的错误);

•header 后面的东西还会执行的.

Tags: header函数 php函数详解

分享到: