HTTP 相关函数库

字体大小: 中小 标准 ->行高大小: 标准
header: 送出 http 协议的标头到浏览器
setcookie: 送出 cookie 信息到浏览器。

header
送出 http 协议的标头到浏览器
语法: int header(string string);
返回值: 整数
函数种类: 网络系统

内容说明: 标头 (header) 是服务器以 http 协议传 html 资料到浏览器前所送出的字符串,在标头与 html 文件之间尚需空一行分隔。有关 http 的详细说明,可以参考坊间的相关书籍或更详细的 rfc 2068 官方文件(http://www.w3.org/protocols/rfc2068/rfc2068)。在 php 中送回 html 资料前,需先传完所有的标头。

注意: 传统的标头一定包含下面三种标头之一,并只能出现一次。

content-type: xxxx/yyyy
location: xxxx:yyyy/zzzz
status: nnn xxxxxx
在新的多型标头规格 (multipart mime) 方可以出现二次以上。

使用范例
范例一: 本例用来重导用户到 php 的官方网站。
<?php
header("location: http://www.php.net");
exit;
?>

范例二: 欲让用户每次都能得到最新的资料,而不是 proxy 或 cache 中的资料,可以使用下列的标头
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");

范例三: 让用户的浏览器出现找不到文件的信息。
<?php
header("status: 404 not found");
?>

范例四: bill@evil.inetarena.com (28-apr-1999) 提供让用户下载文件的范例。
header("content-type: application/x-gzip");
header("content-disposition: attachment; filename=some-file.tar.gz");
header("content-description: php3 generated data");

setcookie
送出 cookie 信息到浏览器。
语法: int setcookie(string name, string value, int expire, string path, string domain, int secure);
返回值: 整数
函数种类: 网络系统

内容说明: 本函数会跟着标头 header 送出一段小信息字符串到浏览器。使用本函数要在送出 html 资料前,实际上 cookie 也算标头的一部份。本函数的参数除了第一个 name 之外,都是可以省略的。参数 name 表示 cookie 的名称;value 表示这个 cookie 的值,这个参数为空字符串则表示取消浏览器中该 cookie 的资料;expire 表示该 cookie 的有效时间;path 为该 cookie 的相关路径;domain 表示 cookie 的网站;secure 则需在 https 的安全传输时才有效。想得到更多的 cookie 信息可以到 http://www.netscape.com/newsref/std/cookie_spec.html,由 cookie 原创者 netscape 所提供的完整信息。

使用范例
dante@mpath.com (27-may-1999) 所提供的 setcookie() 及 header() 范例。
<?php
$status = 0;
if (isset($mytstcky) && ($mytstcky == "chocchip")) $status = 1;
if (!isset($cchk)) {
setcookie("mytstcky", "chocchip");
header("location: $php_self?cchk=1");
exit;
}
?>
<html>
<head><title>cookie check</title></head>
<body bgcolor="#ffffff" text="#000000">
cookie check status:
<?php
printf ('<font color="#%s">%s</font><br>;',
$status ? "00ff00" : "ff0000",
$status ? "passed!" : "failed!");
?>
</body>
</html>

此文章由 http://www.ositren.com 收集整理 ,地址为: http://www.ositren.com/htmls/627.html