zoukankan      html  css  js  c++  java
  • php header运用细节

    http://www.111cn.net/phper/php-function/55872.htm

    http://blog.sina.com.cn/s/blog_7298f36f01011dxv.html

    header的用法

    header()函数的作用是:发送一个原始 HTTP 标头[Http Header]到客户端。

    标头 (header) 是服务器以 HTTP 协义传 HTML 资料到浏览器前所送出的字串,在标头

    与 HTML 文件之间尚需空一行分隔。有关 HTTP 的详细说明,可以参 RFC 2068 官方文件

    (http://www.w3.org/Protocols/rfc2068/rfc2068)。

    在 PHP 中送回 HTML 资料前,需先 传完所有的标头。

    使用范例

    范例一: 本例使浏览器重定向到 PHP 的官方网站。

    <?PHP

    Header("Location: http://www.php.net";);

    exit; //在每个重定向之后都必须加上“exit",避免发生错误后,继续执行。

    ?>

    <?php

    header("refresh:3;url=http://axgle.za.net");

    print('正在加载,请稍等...<br>三秒后自动跳转~~~');

    header重定向 就等价于替用户在地址栏输入url

    ?>

    范例二:禁止页面在IE中缓存

    要使用者每次都能得到最新的资料,而不是 Proxy 或 cache 中的资料,可以使用下列的标头

    <?PHP

    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-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='yourfile.jpg'>"; //通常读取的是缓存文件

    ?>

    <?

    print "<img src='yourfile.jpg?".time()."'>"; //增加了唯一的编号,使浏览器重新请求

    w//print "<img src='yourfile.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.example.org/');

    //文件延迟转向:

    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';

    ?>

    转自旭日达网络


    header() 函数向客户端发送原始的 HTTP 报头,主要包括有HTTP协议的版本、状态代码、原因短语等我们常用于跳转页面,状态发送与文件下载,下面我们一起来看看。

    header分为三部分:

    第一部分为HTTP协议的版本(HTTP-Version);
    第二部分为状态代码(Status);
    第三部分为原因短语(Reason-Phrase)。

    header()函数使用说明: 

    一、作用:   
    ~~~~~~~~~   
           PHP只是以HTTP协议将HTML文档的标头送到浏览器,告诉浏览器具体怎么处理这个页面,至于传送的内容则需要熟悉一下HTTP协议了,与PHP无关了,可参照http://www.w3.org/Protocols/rfc2616/rfc2616。   
           传统的标头一定包含下面三种标头之一,并只能出现一次。   
           Location:  xxxx:yyyy/zzzz   
           Content-Type:  xxxx/yyyy   
           Status:  nnn  xxxxxx 

    二、先来了解一下HTTP协议的运作方式   
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   
           HTTP协议是基于请求/响应范式的。一个客户机与服务器建立连接后,发送一个请求给服务器,请求方式的格式为,统一资源标识符、协议版本号,后边是MIME信息包括请求修饰符、客户机信息和可能的内容。服务器接到请求后,给予相应的响应信息,其格式为一个状态行包括信息的协议版本号、一个成功或错误的代码,后边是MIME信息包括服务器信息、实体信息和可能的内容。   
           它分四个过程,在HTTP协议中,服务端是指提供HTTP服务的部分,客户端是指你使用的浏览器或者下载工具等等。在通讯时,由客户端发出请求连接,服务端建立连接;然后,客户端发出HTTP请求(Request),服务端返回响应信息(Respond),由此完成一个HTTP操作。 

    三、HTTP协议状态码表示的意思   
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~   
    1×× 保留   
    2×× 表示请求成功地接收   
    3×× 为完成请求客户需进一步细化请求   
    4×× 客户错误   
    5×× 服务器错误 

    代码如下
    复制代码

    // fix 404 pages: 用这个header指令来解决URL重写产生的404 header
    header(‘HTTP/1.1 200 OK’);

    // set 404 header: 页面没找到
    header(‘HTTP/1.1 404 Not Found’);

    // 页面被永久删除,可以告诉seo/seo.html" target="_blank">搜索引擎更新它们的urls
    // set Moved Permanently header (good for redrictions)
    // use with location header
    header(‘HTTP/1.1 301 Moved Permanently’);
    // 访问受限
    header(‘HTTP/1.1 403 Forbidden’);
    // 服务器错误
    header(‘HTTP/1.1 500 Internal Server Error’);

    // 重定向到一个新的位置
    // redirect to a new location:
    header(‘Location: http://www.m-bang.com);

    延迟一段时间后重定向
    // redrict with delay:
    header(‘Refresh: 10; url=http://www.sina.com.cn’);
    print ‘You will be redirected in 10 seconds’;

    // 覆盖 X-Powered-By value
    // override X-Powered-By: PHP:
    header(‘X-Powered-By: PHP/4.4.0′);
    header(‘X-Powered-By: Brain/0.6b’);

    // 内容语言 (en = English)
    // content language (en = English)
    header(‘Content-language: en’);

    //最后修改时间 (在缓存的时候可以用到)
    // last modified (good for caching)
    $time = time() – 60; // or filemtime($fn), etc
    header(‘Last-Modified: ‘.gmdate(‘D, d M Y H:i:s’, $time).’ GMT’);

    // 告诉浏览器要获取的内容还没有更新
    // header for telling the browser that the content
    // did not get changed
    header(‘HTTP/1.1 304 Not Modified’);

    // 设置内容的长度 (缓存的时候可以用到):
    // set content length (good for caching):
    header(‘Content-Length: 1234′);

    // 用来下载文件:
    // Headers for an download:
    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’);
    // Disable caching of the current document:
    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 pastheader(‘Pragma: no-cache’);
    // set content type:
    header(‘Content-Type: text/html; charset=iso-8859-1′);
    header(‘Content-Type: text/html; charset=utf-8′);
    header(‘Content-Type: text/plain’);

    // plain text file
    header(‘Content-Type: image/jpeg’);

    // JPG picture
    header(‘Content-Type: application/zip’);

    // ZIP file
    header(‘Content-Type: application/pdf’);

    // PDF file
    header(‘Content-Type: audio/mpeg’);

    // Audio MPEG (MP3,…) file
    header(‘Content-Type: application/x-shockwave-flash’);

    // 显示登录对话框,可以用来进行HTTP认证
    // Flash animation// show sign in box
    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 da
    ta’;
    ?>

    现在表单的填写,我们可以用AJAX对用户随时进行验证,进行友好的提示,但是在用户没有留意AJAX友好提示,提交了错误的表单,跳回原页,而填写的信息却全部丢失了。要支持页面回跳,有以下的办法:
    1. 使用session_cache_limiter方法: session_cache_limiter(‘private,must-revalidate’);但是要值得注意的是 session_cache_limiter()方法要写在session_start()方法之前才有用;
    2.用header来设置控制缓存的方法: header(‘Cache-control:private,must-revalidate’);

    页面跳转要注意的几个问题总结

    1、location和“:”号间不能有空格,否则会出错。 
    2、在用header前不能有任何的输出。 
    3、header后的PHP代码还会被执行。

  • 相关阅读:
    SpringMVC拦截器
    SpringMVC异常
    SpringMVC文件上传
    SpringMVC返回值类型
    JVM字节码
    使用Apache JMeter进行测试
    Tomcat优化
    垃圾收集器
    GC常见算法
    VisualVM远程连接Tomcat
  • 原文地址:https://www.cnblogs.com/ryanlamp/p/4719892.html
Copyright © 2011-2022 走看看