©
Ce document utilise Manuel du site Web PHP chinois Libérer
(PHP 4, PHP 5)
header — 发送原生 HTTP 头
$string
[, bool $replace
= true
[, int $http_response_code
]] )header() 用于发送原生的 HTTP 头。关于 HTTP 头的更多信息请参考 » HTTP/1.1 specification。
请注意 header() 必须在任何实际输出之前调用,不管是普通的 HTML 标签,还是文件或 PHP 输出的空行,空格。这是个常见的错误,在通过 include , require ,或者其访问其他文件里面的函数的时候,如果在 header() 被调用之前,其中有空格或者空行。 同样的问题也存在于单独的 PHP/HTML 文件中。
<html>
<?php
header ( 'Location: http://www.example.com/' );
exit;
?>
string
头字符串。
有两种特别的头。第一种以“HTTP/”开头的 (case is not significant),将会被用来计算出将要发送的HTTP状态码。 例如在 Apache 服务器上用 PHP 脚本来处理不存在文件的请求(使用 ErrorDocument 指令), 就会希望脚本响应了正确的状态码。
<?php
header ( "HTTP/1.0 404 Not Found" );
?>
第二种特殊情况是“Location:”的头信息。它不仅把报文发送给浏览器,而且还将返回给浏览器一个 REDIRECT(302)的状态码,除非状态码已经事先被设置为了201或者3xx。
<?php
header ( "Location: http://www.example.com/" );
exit;
?>
replace
可选参数 replace
表明是否用后面的头替换前面相同类型的头。
默认情况下会替换。如果传入 FALSE
,就可以强制使相同的头信息并存。例如:
<?php
header ( 'WWW-Authenticate: Negotiate' );
header ( 'WWW-Authenticate: NTLM' , false );
?>
http_response_code
强制指定HTTP响应的值。注意,这个参数只有在报文字符串(string
)不为空的情况下才有效。
没有返回值。
版本 | 说明 |
---|---|
5.1.2 | 这个函数现在可以一次性阻止多个报文信息的发送,从而作为对报文信息注入攻击的一种防护。 |
Example #1 下载对话框
如果你想提醒用户去保存你发送的数据,例如保存一个生成的PDF文件。你可以使用» Content-Disposition的报文信息来提供一个推荐的文件名,并且强制浏览器显示一个文件下载的对话框。
<?php
// We'll be outputting a PDF
header ( 'Content-type: application/pdf' );
// It will be called downloaded.pdf
header ( 'Content-Disposition: attachment; filename="downloaded.pdf"' );
// The PDF source is in original.pdf
readfile ( 'original.pdf' );
?>
Example #2 缓存指令
PHP脚本总是会生成一些动态内容,而这些内容是不应该被缓存的,不管是客户端浏览器还是在服务器端和客户端浏览器之间的任何代理。我们可以像这样来强制设置浏览器和各个代理层不缓存数据:
<?php
header ( "Cache-Control: no-cache, must-revalidate" ); // HTTP/1.1
header ( "Expires: Sat, 26 Jul 1997 05:00:00 GMT" ); // Date in the past
?>
Note:
也许你会遇到这样的情况,那就是即使你没使用上面这段代码,你的页面也没有被缓存。大多数情况是因为用户可以自己设置他们的浏览器从而改变浏览器默认的缓存行为。一旦发送了上面这段报文信息,那么你就应该重写那些可能用到缓存了的代码。
此外,在启用session的情况下, session_cache_limiter() 和session.cache_limiter的配置可以用来自动地生成正确的缓存相关的头信息。
Note:
数据头只会在SAPI支持时得到处理和输出。
Note:
你所有需要输出到浏览器的数据将会一直缓存在服务器端,直到你发送他们,这将造成比较大的资源开销。你可以是用输出缓冲来避开这个问题。你可以通过在脚本里使用 ob_start() 和 ob_end_flush() 或者直接在你的php.ini文件里设置output_buffering,也可以直接在服务器的配置文件里设置。
Note:
HTTP状态信息的报文永远都是最新被发送到客户端的,而不管 header() 是否是在最先发送的。报文状态码可能会被重写,当调用 header() 来设定新的状态码,除非HTTP报文已经被发送了。
Note:
在IE 4.01和IE 5.5里有bug,要解决就升级浏览器吧,想必也没人用那么远古的神器了吧。
Note: 如果安全模式(safe mode)被激活,那么脚本的uid将会被添加到WWW-Authenticate的realm部分,前提是你设置了这个头信息的情况下(使用 HTTP 认证)。
Note:
HTTP/1.1需要一个绝对的网络资源地址(URI)来作为一个参数供» Location:使用,在其中必须包含了协议,主机地址还有完整的路径,但是一些客户端可以接受相对的网络资源地址。你可以在一个相对的网路资源地址的基础上使用 $_SERVER['HTTP_HOST'] , $_SERVER['PHP_SELF'] 和 dirname() 来组装一个绝对的网路资源地址。
<?php
$host = $_SERVER [ 'HTTP_HOST' ];
$uri = rtrim ( dirname ( $_SERVER [ 'PHP_SELF' ]), '/\\' );
$extra = 'mypage.php' ;
header ( "Location: http:// $host$uri / $extra " );
exit;
?>
Note:
在执行Location header跳转的时候,Session ID无法通传递的,即使session.use_trans_sid是激活状态的。只能通过手动传递using
SID
的值来实现。
[#1] er dot ellison dot nyc at gmail dot com [2015-10-23 08:16:17]
DO NOT PUT space between location and the colon that comes after that ,
// DO NOT USE THIS :
header("Location : #whatever"); // -> will not work !
// INSTEAD USE THIS ->
header("Location: #wahtever"); // -> will work forever !
[#2] DC [2014-12-18 13:14:32]
In the bottom note:
<?php
$uri = rtrim(dirname($_SERVER['REQUEST_URI']), '/\\');
?>
not $_SERVER['PHP_SELF']!
(But the strange behaviour of dirname is a problem for URL ending by a directory without file name!)
[#3] Vinay Kotekar [2014-12-12 13:34:03]
Saving php file in ANSI no isuess but when saving the file in UTF-8 format for various reasons remember to save the file without any BOM ( byte-order mark) support.
Otherwise you will face problem of headers not being properly sent
eg.
<?php header("Set-Cookie: name=user");?>
Would give something like this :-
Warning: Cannot modify header information - headers already sent by (output started at C:\www\info.php:1) in C:\www\info.php on line 1
[#4] dheeraj dot br2 at gmail dot com [2014-09-26 05:50:39]
The piece of code in the manual which is as follows
<html>
<?php
header('Location: http://www.example.com/');
exit;
?>
this will not throw a warning as the .ini settings for output buffering is by default on.
to get the error you may have to change the server setting or simply add a line explicitly to close output buffering by using "ob_end_clean()" or similar
[#5] ben at indietorrent dot org [2012-05-23 17:34:10]
Be aware that sending binary files to the user-agent (browser) over an encrypted connection (SSL/TLS) will fail in IE (Internet Explorer) versions 5, 6, 7, and 8 if any of the following headers is included:
Cache-control:no-store
Cache-control:no-cache
See: http://support.microsoft.com/kb/323308
Workaround: do not send those headers.
Also, be aware that IE versions 5, 6, 7, and 8 double-compress already-compressed files and do not reverse the process correctly, so ZIP files and similar are corrupted on download.
Workaround: disable compression (beyond text/html) for these particular versions of IE, e.g., using Apache's "BrowserMatch" directive. The following example disables compression in all versions of IE:
BrowserMatch ".*MSIE.*" gzip-only-text/html
[#6] cedric at gn dot apc dot org [2011-01-22 11:47:13]
Setting a Location header "returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set". If you are sending a response to a POST request, you might want to look at RFC 2616 sections 10.3.3 and 10.3.4. It is suggested that if you want the browser to immediately GET the resource in the Location header in this circumstance, you should use a 303 status code not the 302 (with the same link as hypertext in the body for very old browsers). This may have (rare) consequences as mentioned in bug 42969.
[#7] Cody G. [2010-08-01 21:53:20]
After lots of research and testing, I'd like to share my findings about my problems with Internet Explorer and file downloads.
Take a look at this code, which replicates the normal download of a Javascript:
<?php
if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
header("Content-type: text/javascript");
header("Content-Disposition: inline; filename=\"download.js\"");
header("Content-Length: ".filesize("my-file.js"));
} else {
header("Content-type: application/force-download");
header("Content-Disposition: attachment; filename=\"download.js\"");
header("Content-Length: ".filesize("my-file.js"));
}
header("Expires: Fri, 01 Jan 2010 05:00:00 GMT");
if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
header("Cache-Control: no-cache");
header("Pragma: no-cache");
}
include("my-file.js");
?>
Now let me explain:
I start out by checking for IE, then if not IE, I set Content-type (case-sensitive) to JS and set Content-Disposition (every header is case-sensitive from now on) to inline, because most browsers outside of IE like to display JS inline. (User may change settings). The Content-Length header is required by some browsers to activate download box. Then, if it is IE, the "application/force-download" Content-type is sometimes required to show the download box. Use this if you don't want your PDF to display in the browser (in IE). I use it here to make sure the box opens. Anyway, I set the Content-Disposition to attachment because I already know that the box will appear. Then I have the Content-Length again.
Now, here's my big point. I have the Cache-Control and Pragma headers sent only if not IE. THESE HEADERS WILL PREVENT DOWNLOAD ON IE!!! Only use the Expires header, after all, it will require the file to be downloaded again the next time. This is not a bug! IE stores downloads in the Temporary Internet Files folder until the download is complete. I know this because once I downloaded a huge file to My Documents, but the Download Dialog box put it in the Temp folder and moved it at the end. Just think about it. If IE requires the file to be downloaded to the Temp folder, setting the Cache-Control and Pragma headers will cause an error!
I hope this saves someone some time!
~Cody G.
[#8] Marcel G [2010-04-01 18:37:13]
Several times this one is asked on the net but an answer could not be found in the docs on php.net ...
If you want to redirect an user and tell him he will be redirected, e. g. "You will be redirected in about 5 secs. If not, click here." you cannot use header( 'Location: ...' ) as you can't sent any output before the headers are sent.
So, either you have to use the HTML meta refresh thingy or you use the following:
<?php
header( "refresh:5;url=wherever.php" );
echo 'You\'ll be redirected in about 5 secs. If not, click <a href="wherever.php">here</a>.';
?>
Hth someone
[#9] Refugnic [2010-02-03 05:43:55]
My files are in a compressed state (bz2). When the user clicks the link, I want them to get the uncompressed version of the file.
After decompressing the file, I ran into the problem, that the download dialog would always pop up, even when I told the dialog to 'Always perform this operation with this file type'.
As I found out, the problem was in the header directive 'Content-Disposition', namely the 'attachment' directive.
If you want your browser to simulate a plain link to a file, either change 'attachment' to 'inline' or omit it alltogether and you'll be fine.
This took me a while to figure out and I hope it will help someone else out there, who runs into the same problem.
[#10] this dot person at joaocunha dot eti dot br [2010-01-26 10:39:00]
AVOID ZERO BYTE ORDER MARK!
Header MUST be sent before EVERYTHING in the page. Even a single space will break your script. In my case, there was BOM setted in the encoding, so I opened the file with notepad++ and set the encoding to UTF-8 (no BOM) and voila, everything is working great now.
[#11] dev at omikrosys dot com [2009-10-16 22:45:29]
Just to inform you all, do not get confused between Content-Transfer-Encoding and Content-Encoding
Content-Transfer-Encoding specifies the encoding used to transfer the data within the HTTP protocol, like raw binary or base64. (binary is more compact than base64. base64 having 33% overhead).
Eg Use:- header('Content-Transfer-Encoding: binary');
Content-Encoding is used to apply things like gzip compression to the content/data.
Eg Use:- header('Content-Encoding: gzip');
[#12] scott at lucentminds dot com [2009-10-16 16:42:10]
If you want to remove a header and keep it from being sent as part of the header response, just provide nothing as the header value after the header name. For example...
PHP, by default, always returns the following header:
"Content-Type: text/html"
Which your entire header response will look like
HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Content-Type: text/html; charset=UTF-8
Connection: close
If you call the header name with no value like so...
<?php
header( 'Content-Type:' );
?>
Your headers now look like this:
HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Connection: close
[#13] Anonymous [2009-07-31 08:02:40]
I just want to add, becuase I see here lots of wrong formated headers.
1. All used headers have first letters uppercase, so you MUST follow this. For example:
Location, not location
Content-Type, not content-type, nor CONTENT-TYPE
2. Then there MUST be colon and space, like
good: header("Content-Type: text/plain");
wrong: header("Content-Type:text/plain");
3. Location header MUST be absolute uri with scheme, domain, port, path, etc.
good: header("Location: http://www.example.com/something.php?a=1");
4. Relative URIs are NOT allowed
wrong: Location: /something.php?a=1
wrong: Location: ?a=1
It will make proxy server and http clients happier.
[#14] mjt at jpeto dot net [2009-07-17 23:01:32]
I strongly recommend, that you use
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
instead of
header("HTTP/1.1 404 Not Found");
I had big troubles with an Apache/2.0.59 (Unix) answering in HTTP/1.0 while I (accidentially) added a "HTTP/1.1 200 Ok" - Header.
Most of the pages were displayed correct, but on some of them apache added weird content to it:
A 4-digits HexCode on top of the page (before any output of my php script), seems to be some kind of checksum, because it changes from page to page and browser to browser. (same code for same page and browser)
"0" at the bottom of the page (after the complete output of my php script)
It took me quite a while to find out about the wrong protocol in the HTTP-header.
[#15] Jamesb [2009-03-08 05:25:57]
Here is a php script I wrote to stream a file and crypt it with a xor operation on the bytes and with a key :
The encryption works very good but the speed is decrease by 2, it is now 520KiB/s. The user is now asked for a md5 password (instead of keeping it in the code directly). There is some part in French because it's my native language so modify it as you want.
<?php
// Stream files and encrypt the data on-the-fly
// Settings
// -- File to stream
$file = "FILE_out";
// -- Reading buffer
$bufferlength = 3840;
// -- Key in hex
//$keychar = "9cdfb439c7876e703e307864c9167a15";
// Function: Convertion hex key in a string into binary
function hex2bin($h) {
if (!is_string($h)) return null;
$r = array();
for ($a=0; ($a*2)<strlen($h); $a++) {
$ta = hexdec($h[2*$a]);
$tb = hexdec($h[(2*$a+1)]);
$r[$a] = (int) (($ta << 4) + $tb);
}
return $r;
}
// Function to send the auth headers
function askPassword($text="Enter the password") {
header('WWW-Authenticate: Basic realm="'. utf8_decode($text) .'"');
header('HTTP/1.0 401 Unauthorized');
return 1;
}
// Key is asked at the first start
if (!isset($_SERVER['PHP_AUTH_PW'])) {
askPassword();
echo "Une cl?? est n??cessaire !<br />";
exit;
}
// Get the key in hex
$keychar = $_SERVER['PHP_AUTH_PW'];
// Convert key and set the size of the key
$key = hex2bin($keychar);
$keylength = count($key);
// Teste si la cl?? est valide en hex
if ($key == "" || $keylength <= 4) {
askPassword("Cl?? incorrecte !");
//echo "Cl?? incorrecte !<br />";
exit();
}
// Teste si la cl?? est de longueur d'une puissance de 2
if ( ($keylength%2) != 0) {
askPassword("Cl?? de longueur incorrecte (multiple de 2 uniquement)");
//echo "Cl?? de longueur incorrecte (puissance de 2 uniquement)<br />";
exit();
}
// Headers
header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($file) ."; ");
header("filename=\"".$file."\"; ");
flush(); // this doesn't really matter.
// Opening the file in read-only
$fp = fopen($file, "r");
while (!feof($fp))
{
// Read a buffer size of the file
$buffer = fread($fp, $bufferlength);
$j=0;
for ($i=0; $i < $bufferlength; $i++) {
// The key is read in loop to crypt the whole file
if ($i%$keylength == 0) {
$j=0;
}
// Apply a xor operation between the key and the file to crypt
// This operation eats a lots of CPU time (Stream at 1MiB/s on my server; Intel E2180)
$tmp = pack("C", $key[$j]);
$bufferE = ( $buffer[$i]^$tmp); // <==== Le fameux XOR
// Send the encrypted data
echo $bufferE;
// Clean the memory
$bufferE = "";
$j++;
}
$buffer = "";
flush(); // this is essential for large downloads
}
// Close the file and it's finished
fclose($fp);
?>
[#16] bebertjean at yahoo dot fr [2008-12-05 05:46:41]
If using the 'header' function for the downloading of files, especially if you're passing the filename as a variable, remember to surround the filename with double quotes, otherwise you'll have problems in Firefox as soon as there's a space in the filename.
So instead of typing:
<?php
header("Content-Disposition: attachment; filename=" . basename($filename));
?>
you should type:
<?php
header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\"");
?>
If you don't do this then when the user clicks on the link for a file named "Example file with spaces.txt", then Firefox's Save As dialog box will give it the name "Example", and it will have no extension.
See the page called "Filenames_with_spaces_are_truncated_upon_download" at
http://kb.mozillazine.org/ for more information. (Sorry, the site won't let me post such a long link...)
[#17] jamie [2008-12-01 07:57:05]
The encoding of a file is discovered by the Content-Type, either in the HTML meta tag or as part of the HTTP header. Thus, the server and browser does not need - nor expect - a Unicode file to begin with a BOM mark. BOMs can confuse *nix systems too. More info at http://unicode.org/faq/utf_bom.html#bom1
On another note: Safari can display CMYK images (at least the OS X version, because it uses the services of QuickTime)
[#18] mzheng[no-spam-thx] at ariba dot com [2008-10-23 08:50:58]
For large files (100+ MBs), I found that it is essential to flush the file content ASAP, otherwise the download dialog doesn't show until a long time or never.
<?php
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
?>
[#19] shutout2730 at yahoo dot com [2008-08-21 23:57:01]
It is important to note that headers are actually sent when the first byte is output to the browser. If you are replacing headers in your scripts, this means that the placement of echo/print statements and output buffers may actually impact which headers are sent. In the case of redirects, if you forget to terminate your script after sending the header, adding a buffer or sending a character may change which page your users are sent to.
This redirects to 2.html since the second header replaces the first.
<?php
header("location: 1.html");
header("location: 2.html"); //replaces 1.html
?>
This redirects to 1.html since the header is sent as soon as the echo happens. You also won't see any "headers already sent" errors because the browser follows the redirect before it can display the error.
<?php
header("location: 1.html");
echo "send data";
header("location: 2.html"); //1.html already sent
?>
Wrapping the previous example in an output buffer actually changes the behavior of the script! This is because headers aren't sent until the output buffer is flushed.
<?php
ob_start();
header("location: 1.html");
echo "send data";
header("location: 2.html"); //replaces 1.html
ob_end_flush(); //now the headers are sent
?>
[#20] sk89q [2008-08-16 23:41:18]
You can use HTTP's etags and last modified dates to ensure that you're not sending the browser data it already has cached.
<?php
$last_modified_time = filemtime($file);
$etag = md5_file($file);
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
header("Etag: $etag");
if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time ||
trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
header("HTTP/1.1 304 Not Modified");
exit;
}
?>
[#21] Dylan at WeDefy dot com [2007-10-13 08:17:36]
A quick way to make redirects permanent or temporary is to make use of the $http_response_code parameter in header().
<?php
// 301 Moved Permanently
header("Location: /foo.php",TRUE,301);
// 302 Found
header("Location: /foo.php",TRUE,302);
header("Location: /foo.php");
// 303 See Other
header("Location: /foo.php",TRUE,303);
// 307 Temporary Redirect
header("Location: /foo.php",TRUE,307);
?>
The HTTP status code changes the way browsers and robots handle redirects, so if you are using header(Location:) it's a good idea to set the status code at the same time. Browsers typically re-request a 307 page every time, cache a 302 page for the session, and cache a 301 page for longer, or even indefinitely. Search engines typically transfer "page rank" to the new location for 301 redirects, but not for 302, 303 or 307. If the status code is not specified, header('Location:') defaults to 302.
[#22] Kal [2007-07-29 13:07:25]
I spent a long time trying to determine why Internet Explorer 7 wasn't prompting the user to save a download based on the filename specified on a "'Content-Disposition: attachment; filename=..." header line.
I eventually determined that my Apache installation was adding an additional header: "Vary: Host", which was throwing IE - as per http://support.microsoft.com/kb/824847
I found manually setting the Vary header from within PHP as follows header('Vary: User-Agent'); allowed IE to behave as intended.
Hope this saves someone else some time,
- Kal
[#23] nobileelpirata at hotmail dot com [2007-06-02 15:04:17]
This is the Headers to force a browser to use fresh content (no caching) in HTTP/1.0 and HTTP/1.1:
<?PHP
header( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' );
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Cache-Control: post-check=0, pre-check=0', false );
header( 'Pragma: no-cache' );
?>
[#24] mandor at mandor dot net [2006-02-14 17:14:51]
When using PHP to output an image, it won't be cached by the client so if you don't want them to download the image each time they reload the page, you will need to emulate part of the HTTP protocol.
Here's how:
<?php
// Test image.
$fn = '/test/foo.png';
// Getting headers sent by the client.
$headers = apache_request_headers();
// Checking if the client is validating his cache and if it is current.
if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == filemtime($fn))) {
// Client's cache IS current, so we just respond '304 Not Modified'.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 304);
} else {
// Image not cached or cache outdated, we respond '200 OK' and output the image.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 200);
header('Content-Length: '.filesize($fn));
header('Content-Type: image/png');
print file_get_contents($fn);
}
?>
That way foo.png will be properly cached by the client and you'll save bandwith. :)
[#25] jp at webgraphe dot com [2003-11-21 15:56:30]
A call to session_write_close() before the statement
<?php
header("Location: URL");
exit();
?>
is recommended if you want to be sure the session is updated before proceeding to the redirection.
We encountered a situation where the script accessed by the redirection wasn't loading the session correctly because the precedent script hadn't the time to update it (we used a database handler).
JP.
[#26] bMindful at fleetingiamge dot org [2003-05-31 15:08:09]
If you haven't used, HTTP Response 204 can be very convenient. 204 tells the server to immediately termiante this request. This is helpful if you want a javascript (or similar) client-side function to execute a server-side function without refreshing or changing the current webpage. Great for updating database, setting global variables, etc.
header("status: 204"); (or the other call)
header("HTTP/1.0 204 No Response");