PHP header()-funktionen
Definition och användning
header()-funktionen skickar råa HTTP-huvuden till klienten.
Det är viktigt att notera att header()-funktionen måste anropas innan någon faktisk utdata har skickats (i PHP 4 och högre versioner kan du använda output buffering för att lösa detta problem):
<html> <?php // Resultatet är felaktigt // Det finns redan utdata innan anrop av header() header('Location: http://www.example.com/'); ?>
Syntax
header(string,replace,http_response_code)
Parameter | Beskrivning |
---|---|
string | Obligatoriskt. Bestämmer den sträng som ska skickas som huvud. |
replace |
Valfritt. Indikerar om huvudet ska ersätta ett tidigare huvud eller lägga till ett andra huvud. Standard är true (ersätt). false (tillåt flera likadana huvuden). |
http_response_code | 可选。把 HTTP 响应代码强制为指定的值。(PHP 4 以及更高版本可用) |
提示和注释
注释:从 PHP 4.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"); ?> <html> <body> ... ...
注释:用户可能会设置一些选项来更改浏览器的默认缓存设置。通过发送上面的报头,您可以覆盖任何这些设置,强制浏览器不进行缓存!
例子 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"); ?> <html> <body> ... ...
注释:微软 IE 5.5 存在一个阻止以上机制的 bug。通过升级为 Service Pack 2 或更高的版本,可以解决该 bug。