网络编程
位置:首页>> 网络编程>> 网页设计>> HTTP Headers 傻瓜教程[译](6)

HTTP Headers 傻瓜教程[译](6)

 来源:我想网 发布时间:2010-01-25 12:48:00 

标签:http,headers,教程

HTTP Headers 中的 HTTP响应

现在让我了解一些常见的HTTP Headers中的HTTP响应信息。

在PHP中,你可以通过 header() 来设置头部响应信息。PHP已经自动发送了一些必要的头部信息,如 载入的内容,设置 cookies 等等… 你可以通过 headers_list() 函数看到已发送和将要发送的头部信息。你也可以使用headers_sent()函数来检查头部信息是否已经被发送。

Cache-Control

w3.org 的定义是:“The Cache-Control general-header field is used to specify directives which MUST be obeyed by all caching mechanisms along the request/response chain.” 其中“caching mechanisms” 包含一些你ISP可能会用到的 网关和代理信息。

例如:

Cache-Control: max-age=3600, public

“public”意味着这个响应可以被任何人缓存,“max-age” 则表明了该缓存有效的秒数。允许你的网站被缓存降大大减少下载时间和带宽,同时也提高的浏览器的载入速度。

也可以通过设置 “no-cache”  指令来禁止缓存:

Cache-Control: no-cache

更多详情请参见w3.org。

Content-Type

这个头部包含了文档的”mime-type”。浏览器将会依据该参数决定如何对文档进行解析。例如,一个html页面(或者有html输出的php页面)将会返回这样的东西:

Content-Type: text/html; charset=UTF-8

‘text’ 是文档类型,‘html’则是文档子类型。 这个头部还包括了更多信息,例如 charset。

如果是一个图片,将会发送这样的响应:

Content-Type: image/gif

浏览器可以通过mime-type来决定使用外部程序还是自身扩展来打开该文档。如下的例子降调用Adobe Reader:

Content-Type: application/pdf

直接载入,Apache通常会自动判断文档的mime-type并且添加合适的信息到头部去。并且大部分浏览器都有一定程度的容错,在头部未提供或者错误提供该信息的情况下它会去自动检测mime-type。

你可以在这里找到一个常用mime-type列表。

在PHP中你可以通过 finfo_file() 来检测文件的ime-type。

Content-Disposition

这个头部信息将告诉浏览器打开一个文件下载窗口,而不是试图解析该响应的内容。例如:

Content-Disposition: attachment; filename="download.zip"

他会导致浏览器出现这样的对话框:

注意,适合它的Content-Type头信息同时也会被发送

Content-Type: application/zip
Content-Disposition: attachment; filename="download.zip"

Content-Length

当内容将要被传输到浏览器时,服务器可以通过该头部告知浏览器将要传送文件的大小(bytes)。

Content-Length: 89123

对于文件下载来说这个信息相当的有用。这就是为什么浏览器知道下载进度的原因。

例如,这里我写了一段虚拟脚本,来模拟一个慢速下载。

// it's a zip file
header('Content-Type: application/zip');
// 1 million bytes (about 1megabyte)
header('Content-Length: 1000000');
// load a download dialogue, and save it as download.zip
header('Content-Disposition: attachment; filename="download.zip"');
// 1000 times 1000 bytes of data
for ($i = 0; $i < 1000; $i++) {
echo str_repeat(".",1000);
// sleep to slow down the download
usleep(50000);
}

结果将会是这样的:

现在,我将Content-Length头部注释掉:

// it's a zip file
header('Content-Type: application/zip');
// the browser won't know the size
// header('Content-Length: 1000000');
// load a download dialogue, and save it as download.zip
header('Content-Disposition: attachment; filename="download.zip"');
// 1000 times 1000 bytes of data
for ($i = 0; $i < 1000; $i++) {
echo str_repeat(".",1000);
// sleep to slow down the download
usleep(50000);
}

结果就变成了这样:

这个浏览器只会告诉你已下载了多少,但不会告诉你总共需要下载多少。而且进度条也不会显示进度。

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com