PHP header()函数详解

1. 概述

  • header()函数的作用是:发送一个原始HTTP标头到客户端。
  • 头信息是用户看不见的,里面包含了很多项,包括:服务器信息、日期、内容的长度等。
  • 头信息主要的作用为:
    • 跳转:跳转到指定URL地址。
    • 指定网页的内容:浏览器会根据指定的网页格式解析文件。
    • 附件:指定内容为附件,提示浏览器需要保存。

2. 用法

实例1:

// 指定内容为附件
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// 打开文件,并输出
readfile('original.pdf');

实例2:

// 指定内容类型为字节流,浏览器默认下载字节流数据
header("Content-type:application/octet-stream");
// 指定文件长度
header("Accept-Ranges:bytes");
header("Accept-Length:" . filesize($file));
//指定内容为附件
header('Content-Disposition:attachment;filename="downloaded.pdf"');
//指定传输的编码方式
header("Content-Transfer-Encoding:binary");
//打开文件并输出
readfile($file);

3. 更多实例

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

4. 注意

  • PHP向客户端发送HTTP报头之前不能有任何实际的输出,否则会报错。即HTTP报头是需要返回给客户端的首要内容。

参考资料

http://www.lovezbs.com/UPLOAD/?/article/80

http://www.cnblogs.com/cloudlee/archive/2012/10/17/2727434.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值