header()语法

header(string,replace,http_response_code)

 

header()参数

参数 描述
string 必需。规定要发送的报头字符串。
replace

可选。指示该报头是否替换之前的报头,或添加第二个报头。

默认是 true(替换)。false(允许相同类型的多个报头)。

http_response_code 可选。把 HTTP 响应代码强制为指定的值。(PHP 4 以及更高版本可用)

 

header()应用

1、正常访问

header(\'HTTP/1.1 200 OK\');

 

2、页面不存在(404页面)

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

 

3、重定向(状态码302)

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

<##ads_in_article_manong##>

4、永久重定向(状态码301)

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

 

5、延迟转向,也就是隔几秒跳转

header(\'Refresh: 10; url=http://www.manongjc.com/\'); 

 

6、修改 X-Powered-By信息

header(\'X-Powered-By: PHP/6.0.0\');

 

7、设置文档语言

header(\'Content-language: en\'); 

 

8、设置内容长度

header(\'Content-Length: 1234\');

 

9、向客户端浏览器发送文件最后一次修改时间

header(\'Last-Modified: \'.gmdate(\'D, d M Y H:i:s\', $time).\' GMT\');

 

10、告诉浏览器文档内容没有发生改变

header(\'HTTP/1.1 304 Not Modified\');

 

11、设置文件类型

<?php
header(\'Content-Type: text/html; charset=utf-8\'); //网页编码
header(\'Content-Type: text/plain\'); //纯文本格式
header(\'Content-Type: image/jpeg\'); //JPG、JPEG 
header(\'Content-Type: application/zip\'); // ZIP文件
header(\'Content-Type: application/pdf\'); // PDF文件
header(\'Content-Type: audio/mpeg\'); // 音频文件 
header(\'Content-type: text/css\'); //css文件
header(\'Content-type: text/ \'); //js文件
header(\'Content-type: application/json\'); //json
header(\'Content-type: application/pdf\'); //pdf
header(\'Content-type: text/ \'); // 
header(\'Content-Type: application/x-shockw**e-flash\'); //Flash动画
?>

 

12、声明一个下载的文件

<?php
header(\'Content-Type: application/octet-stream\');
header(\'Content-Disposition: attachment; filename=\"ITblog.zip\"\');
header(\'Content-Transfer-Encoding: binary\');
readfile(\'test.zip\');
?>

 

13、对当前文档禁用缓存

<?php
header(\'Cache-Control: no-cache, no-store, max-age=0, must-revalidate\');
header(\'Expires: Mon, 26 Jul 1997 05:00:00 GMT\');
?>

 

14、显示一个需要验证的登陆对话框

<?php
header(\'HTTP/1.1 401 Unauthorized\'); 
header(\'WWW-Authenticate: Basic realm=\"Top Secret\"\');
?>

以上几乎是php header函数在开发中会遇到的设置实例。希望对大家有所帮助。

收藏 打印