PHP Function Reference

PHP header() Function



The PHP header() function is used to send a raw HTTP header. Please note that the header() must be called before any actual output is sent.

Syntax

header(header, replace, response_code)

Parameters

header Required. Specify the header string. There are two special-case header calls:
  • A header that starts with the string "HTTP/" (case is not significant), which is used to figure out the HTTP status code to send. for example - header("HTTP/1.1 404 Not Found");
  • A "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. for example - header("Location: http://www.alphacodingskills.com/");
replace Optional. 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 set to false, it force multiple headers of the same type. For example:
header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false);
response_code Optional. Forces the HTTP response code to the specified value. Note that this parameter only has an effect if the header is not empty.

Return Value

No value is returned.

Exceptions

On failure to schedule the header to be sent, issues an E_WARNING level error.

Example: download dialog

For user to be prompted to save the sent data, such as a generated PDF file, the Content-Disposition header can be used. This is used to supply a recommended filename and forces the browser to display the save dialog.

<?php
//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: 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:

<?php
//Cache-Control 
header("Cache-Control: no-cache, must-revalidate"); 

//date in the past
header("Expires: Mon, 16 Oct 2017 10:30:00 GMT"); 
?>

❮ PHP Network Reference