当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP中header函数的用法及其注意事项详解

PHP中header函数的用法及其注意事项详解

2017年12月12日  | 移动技术网IT编程  | 我要评论

男子掘墓藏26具女尸当玩偶,红河道,凯氏定氮仪

void header ( string $string [, bool $replace = true [, int $http_response_code ]] ) : send a raw http header

下面有一些使用header的几种用法:

1、使用header函数进行跳转页面;

  header('location:'.$url);

  其中$url就是将要跳转的url了。

  这种用法的注意事项有以下几点:

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

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

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

2、使用header声明content-type

  header('content-type:text/html;charset=utf-8');
  这个没有什么好说的;

3、使用header返回response 状态码

  header(sprintf('%s %d %s', $http_version, $status_code, $description));

  样式就是这样的;

  例如:header('http/1.1 404 not found');

4、使用header在某个时间后执行跳转

 header("refresh: {$delay}; url={$url}");

 其中$delay就是推迟跳转的时间,$url为需要跳转的url

 例如:header('refresh: 10; url=http://www.example.org/'); 意思为10s后跳转到http://www.eexample.org这个网站

5、使用header控制浏览器缓存

header("expires: mon, 26 jul 1997 05:00:00 gmt");
  header("last-modified: " . gmdate("d, d m y h:i:s") . "gmt");
  header("cache-control: no-cache, must-revalidate");
  header("pragma: no-cache");

6、执行http验证

  header('http/1.1 401 unauthorized');
  header('www-authenticate: basic realm="top secret"');

7、使用header进行下载操作

header('content-type: application/octet-stream');//设置内容类型
  header('content-disposition: attachment; filename="example.zip"'); //设置mime用户作为附件下载 如果将attachment换成inline意思为在线打开
  header('content-transfer-encoding: binary');//设置传输方式
  header('content-length: '.filesize('example.zip'));//设置内容长度
  // load the file to send:
  readfile('example.zip');//读取需要下载的文件

下面再给大家介绍php header 的几种用法

跳转页面

header('location:'.$url); //location和":"之间无空格。

声明content-type

header('content-type:text/html;charset=utf-8');

返回response状态码

header('http/1.1 404 not found');

在某个时间后执行跳转

header('refresh: 10; url=http://www.baidu.com/'); //10s后跳转。

控制浏览器缓存

header("expires: mon, 26 jul 1997 05:00:00 gmt");
header("last-modified: " . gmdate("d, d m y h:i:s") . "gmt");
header("cache-control: no-cache, must-revalidate");
header("pragma: no-cache");

执行http验证

header('http/1.1 401 unauthorized');
header('www-authenticate: basic realm="top secret"');

执行下载操作

header('content-type: application/octet-stream'); //设置内容类型
header('content-disposition: attachment; filename="example.zip"'); //设置mime用户作为附件
header('content-transfer-encoding: binary'); //设置传输方式
header('content-length: '.filesize('example.zip')); //设置内容长度

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网