当前位置: 移动技术网 > IT编程>开发语言>PHP > 探讨php中header的用法详解

探讨php中header的用法详解

2019年04月10日  | 移动技术网IT编程  | 我要评论
 header() is used to send raw http headers. see the http/1.1 specification for more information on http headers.

范例一:
复制代码 代码如下:

<?php
header("location: //www.jb51.net";);
exit;//在每个重定向之后都必须加上“exit",避免发生错误后,继续执行。
?>

复制代码 代码如下:

<?php
header("refresh:2;url=//www.jb51.net");
echo "正在加载,请稍等...<br>三秒后自动跳转至<a href="//www.jb51.net" mce_href="//www.jb51.net">百度</a>...";
?>

--------------------------------------------------------------------------------
范例二:禁止页面在ie中缓存
使浏览者每次都能得到最新的资料,而不是 proxy 或 cache 中的资料:
复制代码 代码如下:

<?php
header( 'expires: fri, 4 dec 2009 09:00:00 gmt' );
header( 'last-modified: ' . gmdate( 'd, d m y h:i:s' ) . ' gmt' );
header( 'cache-control: no-store, no-cache, must-revalidate' );
header( 'cache-control: post-check=0, pre-check=0', false );
header( 'pragma: no-cache' ); //兼容http1.0和https
?>

cachecontrol = no-cache  pragma=no-cache  expires = -1
如果服务器上的网页经常变化,就把expires设置为-1,表示立即过期。如果一个网页每天凌晨1点更新,可以把expires设置为第二天的凌晨1点。当http1.1服务器指定cachecontrol = no-cache时,浏览器就不会缓存该网页。
旧式 http 1.0 服务器不能使用 cache-control 标题。所以为了向后兼容 http 1.0 服务器,ie使用pragma:no-cache 标题对 http 提供特殊支持。如果客户端通过安全连接 (https://) 与服务器通讯,且服务器在响应中返回 pragma:no-cache 标题,则 internet explorer 不会缓存此响应。
注意:pragma:no-cache 仅当在安全连接中使用时才防止缓存,如果在非安全页中使用,处理方式与 expires:-1 相同,该页将被缓存,但被标记为立即过期。
http-equiv meta标记:
在html页面中可以用http-equiv meta来标记指定的http消息头部。老版本的ie可能不支持html meta标记,所以最好使用http消息头部来禁用缓存。
--------------------------------------------------------------------------------
范例三: 让使用者的浏览器出现找不到档案的信息。
网上很多资料这样写:php的函数header()可以向浏览器发送status标头,
如 header(”status: 404 not found”)。但实际上浏览器返回的响应却是:
复制代码 代码如下:

http/1.x 200 ok
date: thu, 03 aug 2006 07:49:11 gmt
server: apache/2.0.55 (win32) php/5.0.5
x-powered-by: php/5.0.5
status: 404 not found
content-length: 0
keep-alive: timeout=15, max=98
connection: keep-alive
content-type: text/html

查了一些资料,正确的写法是:
header(”http/1.1 404 not found”);
第一部分为http协议的版本(http-version);第二部分为状态代码(status);第三部分为原因短语(reason-phrase)。
--------------------------------------------------------------------------------
范例四:让使用者下载档案( 隐藏文件的位置 )
html标签 就可以实现普通文件下载。如果为了保密文件,就不能把文件链接告诉别人,可以用header函数实现文件下载。
复制代码 代码如下:

<?php
header("content-type: application/x-gzip");
header("content-disposition: attachment; filename=文件名/");
header("content-description: php3 generated data");
?>

范例四:header函数前输入内容
一般来说在header函数前不能输出html内容,类似的还有setcookie() 和 session 函数,这些函数需要在输出流中增加消息头部信息。如果在header()执行之前有echo等语句,当后面遇到header()时,就会报出 “warning: cannot modify header information - headers already sent by ….”错误。就是说在这些函数的前面不能有任何文字、空行、回车等,而且最好在header()函数后加上exit()函数。例如下面的错误写法,在两个php代码段之间有一个空行:
复制代码 代码如下:

//some code here
?>
//这里应该是一个空行
header(”http/1.1 403 forbidden”);
exit();
?>

原因是:php脚本开始执行 时,它可以同时发送http消息头部(标题)信息和主体信息. http消息头部(来自 header() 或 setcookie() 函数)并不会立即发送,相反,它被保存到一个列表中. 这样就可以允许你修改标题信息,包括缺省的标题(例如 content-type 标题).但是,一旦脚本发送了任何非标题的输出(例如,使用 html 或 print() 调用),那么php就必须先发送完所有的header,然后终止 http header.而后继续发送主体数据.从这时开始,任何添加或修改header信息的试图都是不允许的,并会发送上述的错误消息之一。
解决办法:
修改php.ini打开缓存(output_buffering),或者在程序中使用缓存函数ob_start(),ob_end_flush()等。原理是:output_buffering被启用时,在脚本发送输出时,php并不发送http header。相反,它将此输出通过管道(pipe)输入到动态增加的缓存中(只能在php 4.0中使用,它具有中央化的输出机制)。你仍然可以修改/添加header,或者设置cookie,因为header实际上并没有发送。当全部脚本终止时,php将自动发送http header到浏览器,然后再发送输出缓冲中的内容。
=================================================================
php 手册实例应用
1:您可以使用heder命令,强制使浏览器使用新鲜的内容(无缓存) 。
也可以给网址增加了一个唯一的编号,使其每次都读取新的内容,避免缓存。
example:
复制代码 代码如下:

<?
print "<img src="cs.jpg" mce_src="cs.jpg">";   //通常读取的是缓存文件
?>
<?
print "<img src="cs.jpg?".time()."" mce_src="cs.jpg?".time()."">";   //增加了唯一的编号,使浏览器重新请求
w//print "<img src="cs.jpg?".rand(100,999)."" mce_src="cs.jpg?".rand(100,999)."">";
?>

2: 下面是个很好的函数,将图片传送给浏览器显示。
复制代码 代码如下:

<?php
function pe_img_by_path($pe_imgpath = "")
{
    if (file_exists($pe_imgpath)) {
        $pe_imgarray = pathinfo($pe_imgpath);
        $iconcontent = file_get_contents($pe_imgpath);
        header("content-type: image/" . $pe_imgarray["extension"]);
        header('content-length: ' . strlen($iconcontent));
        echo $iconcontent;
        die(0);
    }
    return false;
}
?>

更多的实例:
复制代码 代码如下:

<?php
// ok
header('http/1.1 200 ok');
//设置一个404头:
header('http/1.1 404 not found');
//设置地址被永久的重定向
header('http/1.1 301 moved permanently');
//转到一个新地址
header('location: http://www.baidu.com');
//文件延迟转向:
header('refresh: 10; url=http://www.example.org/');
print 'you will be redirected in 10 seconds';
//当然,也可以使用html语法实现
// <meta http-equiv="refresh" content="10;http://www.example.org/ />
// override x-powered-by: php:
header('x-powered-by: php/4.4.0');
header('x-powered-by: brain/0.6b');
//文档语言
header('content-language: en');
//告诉浏览器最后一次修改时间
$time = time() - 60; // or filemtime($fn), etc
header('last-modified: '.gmdate('d, d m y h:i:s', $time).' gmt');
//告诉浏览器文档内容没有发生改变
header('http/1.1 304 not modified');
//设置内容长度
header('content-length: 1234');
//设置为一个下载类型
header('content-type: application/octet-stream');
header('content-disposition: attachment; filename="example.zip"');
header('content-transfer-encoding: binary');
// load the file to send:
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'); // date in the past
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'); //jpg图片
header('content-type: application/zip'); // zip文件
header('content-type: application/pdf'); // pdf文件
header('content-type: audio/mpeg'); // 音频文件
header('content-type: application/x-shockwave-flash'); //flash动画
//显示登陆对话框
header('http/1.1 401 unauthorized');
header('www-authenticate: basic realm="top secret"');
print 'text that will be displayed if the user hits cancel or ';
print 'enters wrong login data';
?>

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网