header()函数的应用

本文详细介绍了 PHP 中 header 函数的使用方法,包括如何设置 HTTP 响应状态码、进行页面跳转、设置刷新时间、内容类型及长度等。同时展示了如何通过 header 控制缓存策略,以及发送附件下载等常见应用场景。

    
1 备注:使用header()函数前,不能有任何输出,前面放个ob_start就行了
2 // ok
3 header ( ' HTTP/1.1 200 OK ' );
4
5 // 设置一个404头:
6 header ( ' HTTP/1.1 404 Not Found ' );
7
8 // 设置地址被永久的重定向
9 header ( ' HTTP/1.1 301 Moved Permanently ' );
10
11 // 转到一个新地址
12 header ( ' Location: http://www.example.org/ ' );
13
14 // 文件延迟转向:
15 header ( ' Refresh: 10; url=http://www.example.org/ ' );
16 print ' You will be redirected in 10 seconds ' ;
17
18 // 当然,也可以使用html语法实现
19 // <meta http-equiv="refresh" content="10;http://www.example.org/ />
20
21 // override X-Powered-By: PHP:
22 header ( ' X-Powered-By: PHP/4.4.0 ' );
23 header ( ' X-Powered-By: Brain/0.6b ' );
24
25 // 文档语言
26 header ( ' Content-language: en ' );
27
28 // 告诉浏览器最后一次修改时间
29 $time = time () - 60 ; // or filemtime($fn), etc
30 header ( ' Last-Modified: ' . gmdate ( ' D, d M Y H:i:s ' , $time ) . ' GMT ' );
31
32 // 告诉浏览器文档内容没有发生改变
33 header ( ' HTTP/1.1 304 Not Modified ' );
34
35 // 设置内容长度
36 header ( ' Content-Length: 1234 ' );
37
38 // 设置为一个下载类型
39 header ( ' Content-Type: application/octet-stream ' );
40 header ( ' Content-Disposition: attachment; filename="example.zip" ' );
41 header ( ' Content-Transfer-Encoding: binary ' );
42 // load the file to send:
43 readfile ( ' example.zip ' );
44
45 // 对当前文档禁用缓存
46 header ( ' Cache-Control: no-cache, no-store, max-age=0, must-revalidate ' );
47 header ( ' Expires: Mon, 26 Jul 1997 05:00:00 GMT ' ); // Date in the past
48 header ( ' Pragma: no-cache ' );
49
50 // 设置内容类型:
51 header ( ' Content-Type: text/html; charset=iso-8859-1 ' );
52 header ( ' Content-Type: text/html; charset=utf-8 ' );
53 header ( ' Content-Type: text/plain ' ); // 纯文本格式
54 header ( ' Content-Type: image/jpeg ' ); // JPG***
55 header ( ' Content-Type: application/zip ' ); // ZIP文件
56 header ( ' Content-Type: application/pdf ' ); // PDF文件
57 header ( ' Content-Type: audio/mpeg ' ); // 音频文件
58 header ( ' Content-Type: application/x-shockw**e-flash ' ); // Flash动画
59
60 //显示登陆对话框
61 header ( ' HTTP/1.1 401 Unauthorized ' );
62 header ( ' WWW-Authenticate: Basic realm="Top Secret" ' );
63 print ' Text that will be displayed if the user hits cancel or ' ;
64 print ' enters wrong login data ' ;
http://berrywu.javaeye.com/blog/902782

转载于:https://www.cnblogs.com/xwblog/articles/1966559.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值