Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP Network header() Function



The PHP Network header() function is used to transmit raw HTTP headers to the browser before sending any output. Headers are important because they inform the browser how to handle a request or response. For example, headers can be used to redirect a visitor to another page or to set the HTTP status code.

Remember that header() is quite powerful, but it should be used with privacy. If there is any output before invoking it, it will return an error.

Syntax

Below is the syntax of the PHP Network header() function −

void header ( string $header, bool $replace, int $res_code )

Parameters

Here are the parameters of the header() function −

  • $header − (Required) The exact header text to send, like "Location: URL" or "HTTP/1.1 404 Not Found."

  • $replace − (Optional) It determine whether the new header should replace an existing one. By default, it is true.

  • $res_code − (Optional) Sets the HTTP response code as needed.

Return Value

The header() function in PHP does not return any value. Its return type is void.

PHP Version

First introduced in core PHP 4, the header() function continues to function easily in PHP 5, PHP 7, and PHP 8.

Example 1

This program redirects the user to http://www.tutorialspoint.com. It shows a simple way to use the PHP Network header() function for redirection. Always use exit to stop the script from running after a redirect.

<?php
   // Redirect user to another webpage
   header("Location: http://www.tutorialspoint.com/");
   
   echo "The user is redirected.";
   
   // Stop further execution after redirection
   exit;
?>

Output

Here is the outcome of the following code −

The user is redirected.

Example 2

This program sends a custom HTTP status code (404-Not Found) using the header() function. This is useful for manual error handling, like creating a custom error page.

<?php
   // Set a 404 Not Found status code
   header("HTTP/1.1 404 Not Found");
   
   // Output custom error message 
   echo "The page you are looking for was not found.";
?> 

Output

This will generate the below output −

The page you are looking for was not found.

Example 3

The program shows sending several headers of the same type. The $replace option is set to false in order to avoid changing the original header. This is useful when authentication is involved.

<?php
   // Send multiple authentication headers
   header('WWW-Authenticate: Negotiate');

   // Add a second header
   header('WWW-Authenticate: NTLM', false);
   
   // Inform user of the need to authenticate
   echo "Authentication required.";
?> 

Output

This will create the below output −

Authentication required.
php_function_reference.htm
Advertisements