一聚教程网:一个值得你收藏的教程网站

热门教程

PHP中header()函数有什么用?常见header 状态

时间:2022-06-24 15:28:07 编辑:袖梨 来源:一聚教程网

什么是头信息?
这里只作简单解释,详细的自己看http协议。
在 HTTP协议中,服务器端的回答(response)内容包括两部分:头信息(header) 和 体内容,这里的头信息不是HTML中的部分,同样,体内容也不是< /BODY>。头信息是用户看不见的,里面包含了很多项,包括:服务器信息、日期、内容的长度等。而体内容就是整个HTML,也就是你所能看见的全 部东西。

头信息有什么用呢?
头信息的作用很多,最主要的有下面几个:

1、跳转:当浏览器接受到头信息中的 Location: xxxx 后,就会自动跳转到 xxxx 指向的URL地址,这点有点类似用 js 写跳转。但是这个跳转只有浏览器知道,不管体内容里有没有东西,用户都看不到。

2、指定网页的内容: 同样一个XML文件,如果头信息中指定:Content-type: application/xml 的话,浏览器会将其按照XML文件格式解析。但是,如果头信息中是:Content-type: text/xml 的话,浏览器就会将其看作存文本解析。(浏览器不是按照扩展名解析文件的)

3、附件:不知道大家有没 有注意,有些时候在一些网站下载东西,点下载连接以后,结果浏览器将这个附件当成网页打开了,里面显示的都是乱码,这个问题也和头信息有关。有时候浏览器 根据Content-type 来判断是打开还是保存,这样有时就会判断错误(主要是网站设计者忘记写Content-type)。其实,还有一个可以来指定该内容为附件、需要保存,这 个就是:Content-Disposition: attachment; filename=”xxxxx”

在PHP中如何写?
1、跳转:

 代码如下 复制代码
header(“Location: http://www.example.com/”);

2、指定内容:

 代码如下 复制代码
header(‘Content-type: application/pdf’);

3、附件:

 代码如下 复制代码
header(‘Content-type: application/pdf’); // 指定内容格式
header(‘Content-Disposition: attachment; filename=”downloaded.pdf”‘); // 指定内容为附件
readfile(‘original.pdf’); // 打开文件,并输出

最后要提醒大家注意一点,所有头信息都必须在体内容之前,如果一旦有任何输出了的话,header函数写的头信息就没用了。比如,在文件最开头 的

 

 代码如下 复制代码
//200 正常状态
header('HTTP/1.1 200 OK');
 
// 301 永久重定向,记得在后面要加重定向地址 Location:$url
header('HTTP/1.1 301 Moved Permanently');
 
// 重定向,其实就是302 暂时重定向
header('Location: http://www.111com.net/');
 
// 设置页面304 没有修改
header('HTTP/1.1 304 Not Modified');
 
// 显示登录框,
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="登录信息"');
echo '显示的信息!';
 
// 403 禁止访问
header('HTTP/1.1 403 Forbidden');
 
// 404 错误
header('HTTP/1.1 404 Not Found');
 
// 500 服务器错误
header('HTTP/1.1 500 Internal Server Error');
 
// 3秒后重定向指定地址(也就是刷新到新页面与 文件下载
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.zip"');
header('Content-Transfer-Encoding: binary');
readfile('example.zip');//读取文件到客户端
 
//禁用页面缓存
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Pragma: no-cache');
 
//设置页面头信息
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');
header('Content-Type: application/zip');
header('Content-Type: application/pdf');
header('Content-Type: audio/mpeg');
header('Content-Type: application/x-shockwave-flash');
//.... 至于Content-Type 的值 可以去查查 w3c 的文档库,那里很丰富
?>

例,文件下载

 代码如下 复制代码

header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=".$title .".xls ");
header("Content-Transfer-Encoding: binary ");

热门栏目