Heim  >  Artikel  >  Backend-Entwicklung  >  php header()有什么用?

php header()有什么用?

PHPz
PHPzOriginal
2016-06-13 11:54:371840Durchsuche

php header()有什么用?

PHP header()函数可以向客户端发送原始的HTTP报头,即给客户端发送头信息。

什么是头信息?

这里只作简单解释,详细的自己看http协议。

在 HTTP协议中,服务器端的回答(response)内容包括两部分:头信息(header) 和 体内容,这里的头信息不是HTML中的93f0f5c25f18dab9d176bd4f6de5d30e9c3bca370b5104690d9ef395f2c5f8d1部分,同样,体内容也不是a64997a0904a094b4570728d7f327acda0b5ad22ce41154d0eeb328c7ad40487。头信息是用户看不见的,里面包含了很多项,包括:服务器信息、日期、内容的长度等。而体内容就是整个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"

3、附件:

// 指定内容为附件
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// 打开文件,并输出
readfile('original.pdf');

PHP header 的7种用法

1.  跳转页面

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

2.  声明content-type和页面的字符编码

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

3.  返回response状态码

header('HTTP/1.1 404 Not Found');

4. 在某个时间后执行跳转

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

5. 控制浏览器缓存

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('Content-Type: application/octet-stream'); //设置内容类型
header('Content-Disposition: attachment; filename="example.zip"'); //设置MIME用户作为附件
header('Content-Transfer-Encoding: binary'); //设置传输方式
header('Content-Length: '.filesize('example.zip')); //设置内容长度

注意:

所有头信息都必须在体内容之前,如果一旦有任何输出了的话,header函数写的 头信息就没用了。

比如,在文件最开头的<?php 处,如果前面有空格或者有空行,那header函数就没用了(其实可以通过设置:output_buffer来解决,anyway),为什么这样,可以看看HTTP协议,很简单。

更多相关知识,请访问 PHP中文网!!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn