What is the use of header() function in php?


What is the use of header() function in php?

header() function

  1. The header() function in php is use to sends a raw HTTP header to a client.
  2. With the help of header() function we can Change page location, set timezone, set caching control, etc.
  3. It does not return any value means it is a void type
  4. It accept three parameter(i.e.: string, replace and http_response_code)
  5. It is important to 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.


void header ( string $header [, bool $replace = true [, int $http_response_code ]] );



It is required, The header string is call in two spaspecial-case.

1. header that starts with the string "HTTP/" which is used to figure out the HTTP status code to send.

header("HTTP/1.0 404 Not Found");

2. header that stars with the string "Location:" which is used to redirect page.

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

/* Make sure that code below does not get executed when we redirect. */


replace is an optional parameter and is a bool type. it indicates whether the header should replace a previous similar header, or add a second header of the same type. The default is true so it will replace. But if you pass in FALSE as the second argument you can force multiple headers of the same type.

header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false);


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

    // 307 Temporary Redirect
    header("Location: http://www.example.com/", TRUE, 307);


Lets see a block of code with header() function with a common mistake.

// This results in an error.
// The output above is before the header() call
header('Location: http://www.example.com/');

In the above example the code results in an error. because a tag is used before the header() function call.