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

Last updated 5 years, 7 months ago | 1679 views 75     5

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

Syntax

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

 

$header

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.

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

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

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

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

$replace

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.

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

$http_response_code

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

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

 

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

<html>
<?php
// 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.