PHP header() Function Example | header() Method Tutorial

PHP header() is an inbuilt function that can redirect to any URL. The PHP header() function sends the HTTP header to the client or browser in raw form. Remember that the header() must be called before any actual output is sent, either by standard HTML tags, blank lines in the file, or from PHP.  In PHP 4 version and later, you can use output buffering to solve this problem.

PHP header() Function

The HTTP functions are those functions that modify information sent to a client or browser by a Web server before any other output has been sent.  Before HTML, XML, JSON or other output has been sent to the browser or client, and the raw data is sent with the request (especially HTTP Request) made by the server as header information.

HTTP header provides the required data about an object sent in the message body more precisely about the request and response.

#Syntax of header() Function

header( $header, $replace = TRUE, $http_response_code )
  1. $header: The $header parameter holds the header string. There are two types of header calls. The first header starts with the string “HTTP/,” which is used to figure out the HTTP status code to send. The second case of the header is the “Location:”. It is a mandatory parameter.
  2. $replace: The $replace is an optional parameter. It denotes the header should replace previous or add the second header. The default value is True (will replace). If $replace value is False, then it forces multiple headers of the same type.
  3. $http_response_code: The $http_response_code is an optional parameter. It forces an HTTP response code to the specified value (PHP 4.3 and higher).

See the following example.

// Redirect the browser 

#Prevent page caching in PHP

We can prevent page caching by using the header() function.


// PHP program to describes header function 

header("Expires: Sun, 19 February 1994 06:02:34 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");

#Save PDF File

If we want functionality in which lets user be prompted to save a generated PDF file. Then the Content-Disposition header is used to supply the recommended filename and force the browser to display the save dialog box.

See the following code.


// It will be called downloaded.pdf
// The PDF source is in original.pdf

#Other Applications

  1. If we want to change the page location.
  2. If we want to set timezone.
  3. If we want the caching control.
  4. If we want to initiate force download.
  5. If we want to send HTTP Status.

Finally, PHP header() Function Example | header() Method In PHP Tutorial is over.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.