void header ( string $string [, bool $replace = true [, int $http_response_code ]] ) : Send a raw HTTP header
PHP header函数基本用法与注意事项
以下是关于header函数具体用法的几种示例:
1、利用header函数实现页面重定向;
header('Location:'.$url);
这里的$url变量代表目标跳转地址。
使用该方式时需注意以下事项:
• Location关键字与冒号":"之间严禁包含空格,否则会导致跳转失败(注:经测试,在本地环境中可能仅表现为无反应而不报错,具体原因待查);
• 调用header之前绝对不能有输出内容(注:此为常识,若此前存在任何输出,哪怕是空白字符,都会触发“headers already sent by xxx”的错误);
• 执行header语句后,后续代码仍会继续运行;
2、通过header设置Content-Type类型;
header('content-type:text/html;charset=utf-8'); 此用法较为简单,无需过多解释;
3、利用header返回Response状态码;
header(sprintf('%s %d %s', $http_version, $status_code, $description));
格式结构如下所示;
例如:header('HTTP/1.1 404 Not Found');
4、设定延迟时间后进行页面跳转;
header("Refresh: {$delay}; url={$url}");
其中$delay参数表示延迟秒数,$url为目标链接。
例如:header('Refresh: 10; url=http://www.example.org/'); 表示等待10秒后跳转至指定网站。
5、借助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, 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用户作为附件下载 如果将attachment换成inline意思为在线打开
header('Content-Transfer-Encoding: binary');//设置传输方式
header('Content-Length: '.filesize('example.zip'));//设置内容长度
// load the file to send:
readfile('example.zip');//读取需要下载的文件
接下来介绍PHP header的其他几种典型用法。
页面跳转功能
header('Location:'.$url); //注意Location和":"之间不能有空格。
声明Content-Type
header('content-type:text/html;charset=utf-8');
返回Response状态码
header('HTTP/1.1 404 Not Found');
延时跳转
header('Refresh: 10; url=http://www.baidu.com/'); //10秒后执行跳转。
控制浏览器缓存
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");
执行HTTP验证
header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Basic realm="Top Secret"');
执行下载操作
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')); //设定内容长度