PHP header, 函数

定义和用法

header() 函数向客户端发送原始的 HTTP 报头。

语法

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

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

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

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

例子 1

<?php
// Date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
?>

注释:用户可能会设置一些选项来更改浏览器的默认缓存设置。通过发送上面的报头,您可以覆盖任何这些设置,强制浏览器不进行缓存!

例子 2

提示用户保存一个生成的 PDF 文件(Content-Disposition 报头用于提供一个推荐的文件名,并强制浏览器显示保存对话框):

<?php
header("Content-type:application/pdf");

// 文件将被称为 downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");

// PDF 源在 original.pdf 中
readfile("original.pdf");
?>

例子 3

在PHP中用header("location:test.php"):页面跳转

设置字符集:

header("Content-type: text/html; charset=utf-8");