header函数使用

void header ( string $string [, bool $replace = true [, int $http_response_code ]] )

----- 用于向客户端发送原生的 HTTP 报头,

注意 

header() 必须在任何实际输出之前调用,不管是普通的 HTML 标签,还是文件或 PHP 输出的空行,空格。这是个常见的错误,例如在通过include,require,或者其访问其他文件里面的函数的时候,如果在header()被调用之前,其中有空格或者空行。

客户机的请求方式格式:是统一资源标识符、协议版本号,后边是MIME信息包括请求修饰符、客户机信息和可能的内容

服务器响应格式:一个状态行包括信息的协议版本号、一个成功或错误的代码,后边是MIME信息包括服务器信息、实体信息和可能的内容。

常用实例: 1.实现重定向(状态码302) Location

<?php
header(”Location: http://www.phpddt.com”);
exit; 
?>

注意:@1 Location 和:之间没有空格 @2 在每个重定向之后都必须加上“exit”,避免发生错误后,继续执行。

永久重定向(状态码301)

<?
Header( "HTTP/1.1 301 Moved Permanently" ) ;
Header( "Location: www.phpddt.com" );
?>

2.使用header在某个时间后执行跳转

header('Refresh: 10; url=http://www.example.org/')

10秒后跳转到 http://www.example.org/页面

当然,也可以使用html语法实现
//<meta http-equiv="refresh" content="10;http://www.example.org/ />

3.实现文件下载

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强制下载application/force-download,将发送HTTP 标头您的浏览器并告诉它下载,而不是在浏览器中运行的文件。 最主要原理是根据:"Content-Type: application/force-download;"和"Content-Disposition: attachment;"来达到目的。 header("Content-Type: application/force-download;"); //告诉浏览器强制下载

4.设置文件内容类型 Content-Type

<?php
header(’Content-Type: text/html; charset=utf-8′);
header('Content-Type: text/html; charset=iso-8859-1');  
header('Content-Type: text/html; charset=utf-8');  
header('Content-Type: text/plain'); //纯文本格式  
header('Content-Type: image/jpeg'); //JPG***  
header('Content-Type: application/zip'); // ZIP文件  
header('Content-Type: application/pdf'); // PDF文件  
header('Content-Type: audio/mpeg'); // 音频文件  
header('Content-Type: application/x-shockw**e-flash'); //Flash动画 
?>

5.状态码 status

页面不存在(404页面)

<?php 
header('HTTP/1.1 404 Not Found'); 
header("status: 404 Not Found"); 
?> 

6.使用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, no-store, max-age=0, must-revalidate");
  header("Pragma: no-cache");

转载于:https://my.oschina.net/u/2299514/blog/793755

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值