header

(PHP 4, PHP 5, PHP 7, PHP 8)

header发送原生 HTTP 头

说明

header ( string $string , bool $replace = true , int $response_code = ? ) : void

header() 用于发送原生的 HTTP 头。关于 HTTP 头的更多信息请参考 » HTTP/1.1 specification

请注意 header() 必须在任何实际输出之前调用,不管是普通的 HTML 标签,还是文件或 PHP 输出的空行,空格。这是个常见的错误,在通过includerequire,或者其访问其他文件里面的函数的时候,如果在header()被调用之前,其中有空格或者空行。 同样的问题也存在于单独的 PHP/HTML 文件中。

<html>
<?php
/* This will give an error. Note the output
 * above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>

参数

string

头字符串。

有两种特别的头。第一种以"HTTP/"开头的 (case is not significant),将会被用来计算出将要发送的HTTP状态码。 例如在 Apache 服务器上用 PHP 脚本来处理不存在文件的请求(使用 ErrorDocument 指令), 就会希望脚本响应了正确的状态码。

<?php
// 本示例演示了 "HTTP/" 的特殊例子,典型用法的最佳实践,包括:
// 1. header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
//    (覆盖 http 状态消息,兼容还在使用 HTTP/1.0 的客户端)
// 2. http_response_code(404); (使用默认消息)
header("HTTP/1.1 404 Not Found");
?>

第二种特殊情况是"Location:"的头信息。它不仅把报文发送给浏览器,而且还将返回给浏览器一个 REDIRECT(302)的状态码,除非状态码已经事先被设置为了201或者3xx

<?php
header
("Location: http://www.example.com/"); /* Redirect browser */

/* Make sure that code below does not get executed when we redirect. */
exit;
?>

replace

可选参数 replace 表明是否用后面的头替换前面相同类型的头。 默认情况下会替换。如果传入 false,就可以强制使相同的头信息并存。例如:

<?php
header
('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM'false);
?>

response_code

强制指定 HTTP 响应的值。注意,这个参数只有在报文字符串(header)不为空的情况下才有效。

返回值

没有返回值。

错误/异常

当 header 发送失败时,header() 会抛出 E_WARNING 级别的错误

范例

Example #1 下载对话框

如果你想提醒用户去保存你发送的数据,例如保存一个生成的PDF文件。你可以使用» Content-Disposition的报文信息来提供一个推荐的文件名,并且强制浏览器显示一个文件下载的对话框。

<?php
// 输出 PDF 文件
header('Content-type: application/pdf');

// 名称为 downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// 该 PDF 来源于 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"); // 过去的日期
?>

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:

绝大多数现代浏览器的 » Location: 都支持相对 URI,但也有一些旧浏览器需要绝对 URI:包含协议、主机名、绝对路径。 一般情况下,可以借助 $_SERVER['HTTP_HOST']$_SERVER['PHP_SELF']dirname() 将相对地址组合成绝对 URI:

<?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的值来实现。

参见

User Contributed Notes

David Spector 12-Jul-2021 12:07
Please note that there is no error checking for the header command, either in PHP, browsers, or Web Developer Tools.

If you use something like "header('text/javascript');" to set the MIME type for PHP response text (such as for echoed or Included data), you will get an undiagnosed failure.

The proper MIME-setting function is "header('Content-type: text/javascript');".
atesin $ gmail 26-Jun-2020 07:25
CGI (not FastCGI) is easy to learn and good for small http servers ... i am writing one to learn programming (python)... that lead me to research php-cgi internals
.

php running in CGI mode works like this:

- if we type "php-cgi[.exe]" at console, seems it freezes and nothing happens, but is actually waiting for a valid html/php code from standard input until EOF is reached (*nix: ctrl-d , win: ctrl-z + enter, or an actual piped file or stream)

- we can also enter a php file path as first parameter: "php-cgi /my/php/file"

- the two behaviors described above are disabled when GATEWAY_INTERFACE env-var is set (commonly with "CGI/1.1")

- if php-cgi was compiled with "--enable-force-cgi-redirect" option, it also requires the REDIRECT_STATUS env-var set to "200" (according php and nginx documentation)...

- so the current way to provide the file path is setting the SCRIPT_FILENAME env-var ... it also works with PATH_TRANSLATED but discouraged by security reasons
.

wikipedia and php have good documentation about CGI env-vars:

- https://en.wikipedia.org/wiki/Common_Gateway_Interface
- https://www.php.net/manual/en/reserved.variables.server.php
.

PHP CGI PROCESS

suppose you pass this file/code to php-cgi

--------------------------------
<?php echo mt_rand(1000, 999); ?>
--------------------------------

php-cgi standard output will show some like
--------------------------------
X-Powered-By: PHP/7.1.0
Content-type: text/html; CHARSET=gb2312

5806
--------------------------------

note the few included response headers and the lack of status line... seems was made this way to continue previous headers from http server

this let me think about header() function, so i make little more tests

input
--------------------------------
<?php header('Location: http://some.web.page'); ?>
--------------------------------

output
--------------------------------
Status: 302 Found
X-Powered-By: PHP/7.1.0
Location: http://some.web.page
Content-type: text/html; CHARSET=gb2312
--------------------------------

note the new "status code" was not specified through "HTTP/..." status line but instead through a new "Status:" header ...  in fact there are 2 new headers, "Status:" and "Location:" according php header() documentation

this let me think, in cgi mode php header function don't have the access to actually change response status, maybe the cgi specification never intended ... i don't know what would happen with a response with "HTTP/X.Y 200 OK" and later "Status: 123 Other Status", the server should deal the situation

i also realized header() don't have the ability to force replace (via the second paramter) the headers sent by server, at least in cgi mode

cheers
Angelica Perduta 24-Feb-2020 11:20
I made a script that generates an optimized image for use on web pages using a 404 script to resize and reduce original images, but on some servers it was generating the image but then not using it due to some kind of cache somewhere of the 404 status. I managed to get it to work with the following and although I don't quite understand it, I hope my posting here does help others with similar issues:

    header_remove();
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    // ... and then try redirecting
    // 201 = The request has been fulfilled, resulting in the creation of a new resource however it's still not loading
    // 302 "moved temporarily" does seems to load it!
    header("location:$dst", FALSE, 302); // redirect to the file now we have it
php at ober-mail dot de 07-Dec-2019 02:14
Since PHP 5.4, the function `http_?response_?code()` can be used to set the response code instead of using the `header()` function, which requires to also set the correct protocol version (which can lead to problems, as seen in other comments).
hrushiemail at gmail dot com 03-Aug-2018 09:34
[warning : "cannot modify header information"] in php
for fixing this issue follow below steps:

1) open your php.ini file.......
In that php.ini enable the output_buffering

   output_buffering = 1

2) save the file
3) and restart your web server

for linux user type in terminal,
    service httpd restart
hamza dot eljaouhari dot etudes at gmail dot com 06-Jun-2018 07:56
// Beware that adding a space between the keyword "Location" and the colon causes an Internal Sever Error

//This line causes the error
        7
header('Location : index.php&controller=produit&action=index');

// While It must be written without the space
 header('Location: index.php&controller=produit&action=index');
ASchmidt at Anamera dot net 11-May-2018 03:36
Setting the "Location: " header has another undocumented side-effect!

It will also disregard any expressly set "Content-Type: " and forces:

"Content-Type: text/html; CHARSET=gb2312"

The HTTP RFCs don't call for such a drastic action. They simply state that a redirect content SHOULD include a link to the destination page (in which case ANY HTML compatible content type would do). But PHP even overrides a perfectly standards-compliant
"Content-Type: application/xhtml+xml"!
2962051004 at qq dot com 11-Mar-2018 11:36
<?php

/*
In some special cases, to disable a web page from being cached by the browser, the following function can implement this function:
*/
function disabledcache()
{
   
header("Expires: 0"); // 向后兼容HTTP/1.0  
   
header("Pragma: no-cache"); // 支持HTTP/1.1  
   
header("Cache-Control: no-cache,no-store,max-age=0,s-maxage=0,must-revalidate");
}
tim at sharpwebdevelopment dot com 19-Feb-2018 03:18
The header call can be misleading to novice php users.
when "header call" is stated, it refers the the top leftmost position of the file and not the "header()" function itself.
"<?php" opening tag must be placed before anything else, even whitespace.
razvan_bc at yahoo dot com 17-Jan-2018 05:20
<?php
/* This will give an error. Note the output
 * above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>

this example is pretty good BUT in time you use "exit" the parser will still work to decide what's happening next the "exit" 's action should do ('cause if you check the manual exit works in others situations too).
SO MY POINT IS : you should use :
<?php

header
('Location: http://www.example.com/');
die();

?>
'CAUSE all die function does is to stop the script ,there is no other place for interpretation and the scope you choose to break the action of your script is quickly DONE!!!

there are many situations  with others examples and the right choose for small parts of your scrips that make differences when you write your php framework at well!

Thanks Rasmus Lerdorf and his team to wrap off parts of unusual php functionality ,php 7 roolez!!!!!
David 15-Sep-2017 04:26
It seems the note saying the URI must be absolute is obsolete. Found on https://en.wikipedia.org/wiki/HTTP_location

?An obsolete version of the HTTP 1.1 specifications (IETF RFC 2616) required a complete absolute URI for redirection.[2] The IETF HTTP working group found that the most popular web browsers tolerate the passing of a relative URL[3] and, consequently, the updated HTTP 1.1 specifications (IETF RFC 7231) relaxed the original constraint, allowing the use of relative URLs in Location headers.?
chris at ocproducts dot com 21-Jan-2017 06:59
Note that 'session_start' may overwrite your custom cache headers.
To remedy this you need to call:

session_cache_limiter('');

...after you set your custom cache headers. It will tell the PHP session code to not do any cache header changes of its own.
nospam at nospam dot com 17-Mar-2016 08:50
<?php

// Response codes behaviors when using
header('Location: /target.php', true, $code) to forward user to another page:

$code = 301;
// Use when the old page has been "permanently moved and any future requests should be sent to the target page instead. PageRank may be transferred."

$code = 302; (default)
// "Temporary redirect so page is only cached if indicated by a Cache-Control or Expires header field."

$code = 303;
// "This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource and is not cached."

$code = 307;
// Beware that when used after a form is submitted using POST, it would carry over the posted values to the next page, such if target.php contains a form processing script, it will process the submitted info again!

// In other words, use 301 if permanent, 302 if temporary, and 303 if a results page from a submitted form.
// Maybe use 307 if a form processing script has moved.

?>
yjf_victor 19-Jan-2016 02:23
According to the RFC 6226 (https://tools.ietf.org/html/rfc6266), the only way to send Content-Disposition Header with encoding is:

Content-Disposition: attachment;
                          filename*= UTF-8''%e2%82%ac%20rates

for backward compatibility, what should be sent is:

Content-Disposition: attachment;
                          filename="EURO rates";
                          filename*=utf-8''%e2%82%ac%20rates

As a result, we should use

<?php
$filename
= '中文文件名.exe';   // a filename in Chinese characters

$contentDispositionField = 'Content-Disposition: attachment; '
   
. sprintf('filename="%s"; ', rawurlencode($filename))
    .
sprintf("filename*=utf-8''%s", rawurlencode($filename));

header('Content-Type: application/octet-stream');

header($contentDispositionField);

readfile('file_to_download.exe');
?>

I have tested the code in IE6-10, firefox and Chrome.
er dot ellison dot nyc at gmail dot com 23-Oct-2015 08:16
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 !
DC 18-Dec-2014 01:14
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!)
Vinay Kotekar 12-Dec-2014 01:34
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
dheeraj dot br2 at gmail dot com 26-Sep-2014 05:50
The piece of code in the manual which is as follows

<html>
<?php
/* This will give an error. Note the output
 * above, which is before the header() call */
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
ben at indietorrent dot org 23-May-2012 05:34
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
cedric at gn dot apc dot org 22-Jan-2011 11:47
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.
Cody G. 01-Aug-2010 09:53
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.
Marcel G 01-Apr-2010 06:37
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
Refugnic 03-Feb-2010 05:43
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.
this dot person at joaocunha dot eti dot br 26-Jan-2010 10:39
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.
dev at omikrosys dot com 16-Oct-2009 10:45
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');
scott at lucentminds dot com 16-Oct-2009 04:42
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=gb2312
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
Anonymous 31-Jul-2009 08:02
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.
mjt at jpeto dot net 17-Jul-2009 11:01
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.
Jamesb 08-Mar-2009 05:25
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
       
        /*
        echo "<br />key[".$j."]: ";
        var_dump($tmp);
        echo "<br />buffer[".$i."]: ";
        var_dump($buffer[$i]);
        echo "<br />bufferE: ";
        var_dump($bufferE);
        echo "<br />";
        //*/
       
        // Send the encrypted data
       
echo $bufferE;
       
// Clean the memory
       
$bufferE = "";
       
$j++;
    }
   
$buffer = "";
   
flush(); // this is essential for large downloads
    /*
    fclose($fp);
    exit();
    //*/
}
// Close the file and it's finished
fclose($fp);

?>
bebertjean at yahoo dot fr 05-Dec-2008 05:46
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...)
jamie 01-Dec-2008 07:57
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)
mzheng[no-spam-thx] at ariba dot com 23-Oct-2008 08:50
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);
?>
shutout2730 at yahoo dot com 21-Aug-2008 11:57
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
?>
sk89q 16-Aug-2008 11:41
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;
}
?>
Dylan at WeDefy dot com 13-Oct-2007 08:17
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.
Kal 29-Jul-2007 01:07
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
nobileelpirata at hotmail dot com 02-Jun-2007 03:04
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' );

?>
mandor at mandor dot net 14-Feb-2006 05:14
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. :)
jp at webgraphe dot com 21-Nov-2003 03:56
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.
bMindful at fleetingiamge dot org 31-May-2003 03:08
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");
PHP8中文手册 站长在线 整理 版权归PHP文档组所有