Description

Remember that header() must be called before any
actual output is sent, either by normal HTML tags, blank lines in a
file, or from PHP. It is a very common error to read code with
include(), or require(),
functions, or another file access function, and have spaces or empty
lines that are output before header() is called.
The same problem exists when using a single PHP/HTML file.

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

Parameters

string

The header string.

There are two special-case header calls. The first is a header
that starts with the string "HTTP/" (case is not
significant), which will be used to figure out the HTTP status
code to send. For example, if you have configured Apache to
use a PHP script to handle requests for missing files (using
the ErrorDocument directive), you may want to
make sure that your script generates the proper status code.

<?phpheader("HTTP/1.0 404 Not Found");?>

For FastCGI you must use the following for a 404 response:

<?phpheader("Status: 404 Not Found");?>

The second special case is the "Location:" header. Not only does
it send this header back to the browser, but it also returns a
REDIRECT (302) status code to the browser
unless the 201 or
a 3xx status code has already been set.

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

replace

The optional replace parameter indicates
whether the header should replace a previous similar header, or
add a second header of the same type. By default it will replace,
but if you pass in FALSE as the second argument you can force
multiple headers of the same type. For example:

Forces the HTTP response code to the specified value. Note that this
parameter only has an effect if the string is
not empty.

Return Values

No value is returned.

Changelog

Version

Description

4.4.2 and 5.1.2

This function now prevents more than one header to be sent at once as
a protection against header injection attacks.

4.3.0

The http_response_code parameter was added.

4.0.4

The replace parameter was added.

Examples

Example #1 Download dialog

If you want the user to be prompted to save the data you are
sending, such as a generated PDF file, you can use the » Content-Disposition header to
supply a recommended filename and force the browser to display the
save dialog.

// It will be called downloaded.pdfheader('Content-Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdfreadfile('original.pdf');?>

Example #2 Caching directives

PHP scripts often generate dynamic content that must not be cached
by the client browser or any proxy caches between the server and the
client browser. Many proxies and clients can be forced to disable
caching with:

You may find that your pages aren't cached even if you don't
output all of the headers above. There are a number of options
that users may be able to set for their browser that change its
default caching behavior. By sending the headers above, you should
override any settings that may otherwise cause the output of your
script to be cached.

Additionally, session_cache_limiter() and
the session.cache_limiter configuration
setting can be used to automatically generate the correct
caching-related headers when sessions are being used.

Notes

Note:

You can use output buffering to get around this problem,
with the overhead of all of your output to the browser being buffered
in the server until you send it. You can do this by calling
ob_start() and ob_end_flush()
in your script, or setting the output_buffering
configuration directive on in your php.ini or
server configuration files.

Note:

The HTTP status header line will always be the first sent
to the client, regardless of the actual header()
call being the first or not. The status may be overridden
by calling header() with a new status line
at any time unless the HTTP headers have already been sent.

Note:

There is a bug in Microsoft Internet Explorer 4.01 that prevents
this from working. There is no workaround. There is also a bug
in Microsoft Internet Explorer 5.5 that interferes with this,
which can be resolved by upgrading to Service Pack 2 or later.

Note:
If safe mode is enabled the
uid of the script is added to the realm part
of the WWW-Authenticate header if you set
this header (used for HTTP Authentication).

<?php/* Redirect to a different page in the current directory that was requested */$host = $_SERVER['HTTP_HOST'];$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');$extra = 'mypage.php';header("Location: http://$host$uri/$extra");exit;?>

Note:

Session ID is not passed with Location header even if session.use_trans_sid is
enabled. It must by passed manually using SID
constant.

User Contributed Notes 33 notes

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.

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:

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.

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.

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...)

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:

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 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.

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

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!

/*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");}

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.

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

«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.»

// 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.

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

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");

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.

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.

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)

<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

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.

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.