header函数使用

void header ( string $string [, bool $replace = true [, int $http_response_code ]] )php

----- 用于向客户端发送原生的 HTTP 报头,html

注意 浏览器

header() 必须在任何实际输出以前调用,无论是普通的 HTML 标签,仍是文件或 PHP 输出的空行,空格。这是个常见的错误,例如在经过include,require,或者其访问其余文件里面的函数的时候,若是在header()被调用以前,其中有空格或者空行。缓存

客户机的请求方式格式:是统一资源标识符、协议版本号,后边是MIME信息包括请求修饰符、客户机信息和可能的内容服务器

服务器响应格式:一个状态行包括信息的协议版本号、一个成功或错误的代码,后边是MIME信息包括服务器信息、实体信息和可能的内容。app

经常使用实例: 1.实现重定向(状态码302) Location函数

<?php
header(”Location: http://www.phpddt.com”);
exit; 
?>

注意:@1 Location 和:之间没有空格 @2 在每一个重定向以后都必须加上“exit”,避免发生错误后,继续执行。动画

永久重定向(状态码301)ui

<?
Header( "HTTP/1.1 301 Moved Permanently" ) ;
Header( "Location: www.phpddt.com" );
?>

2.使用header在某个时间后执行跳转url

header('Refresh: 10; url=http://www.example.org/')

10秒后跳转到 http://www.example.org/页面

固然,也能够使用html语法实现
//<meta http-equiv="refresh" content="10;http://www.example.org/ />

3.实现文件下载

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强制下载application/force-download,将发送HTTP 标头您的浏览器并告诉它下载,而不是在浏览器中运行的文件。 最主要原理是根据:"Content-Type: application/force-download;"和"Content-Disposition: attachment;"来达到目的。 header("Content-Type: application/force-download;"); //告诉浏览器强制下载

4.设置文件内容类型 Content-Type

<?php
header(’Content-Type: text/html; charset=utf-8′);
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-shockw**e-flash'); //Flash动画 
?>

5.状态码 status

页面不存在(404页面)

<?php 
header('HTTP/1.1 404 Not Found'); 
header("status: 404 Not Found"); 
?>

6.使用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, no-store, max-age=0, must-revalidate");
  header("Pragma: no-cache");
相关文章
相关标签/搜索