PHP’s Header Function

Sending HTTP Headers

The HyperText Transfer Protocal (HTTP) is the language that Web servers and Web clients use to talk to each other over the Internet. PHP’s header() can be used to send raw, arbitrary HTTP headers. You can use it to take advantage of any kind of header-controlled functionality. The syntax of header() takes a single argument, which is the header to be sent.

Example: Redirection

One useful kind of HTTP header is “Location:”, which can act as a redirector. Simply put a URL after the “Location:” string, and the browser will start over again with the new address instead. An example:

if(( isset( $gender )) && ( $gender == “female” )) {
header( “Location:” );

<html><head><title>the inclusive page</title></head>
We welcome anyone to this page even men! Talk amongst yourselves.

If we simply enter the URL for this page (, we will see the rendering of the HTML at the bottom. Or else, if we include the right GET argument (, we find ourselves redirected to a different page entirely. The new Web address then shows up in the “Location” or “Address” bar of your browser.

This kind of redirection can be useful when you want the structure of your site to conditionally “branch” without having to make the user explicitly choose different links.

Example: HTTP authentication

Another useful thing you can do with HTTP is ask the browser to ask the user for a username and password, via a pop-up window. This is done with the WWW-Authenticate header, as in the following example:

$username = ‘username’;
$password = ‘password’;
if ( !isset( $PHP_AUTH_USER ) ) {
Header( “WWW-Authenticate: Basic realm=\”PHP login\”” );
Header( “HTTP/1.0 401 Unauthorized” );
echo “Canceled by user\n”;
} else {
if ( ( $PHP_AUTH_USER == ‘userame’ ) && ( $PHP_AUTH_PW == ‘password’ ) )
print( “The realm is yours<br/>” );
print( “We don’t need your kind<br/>” );

If we visit the script for the first time, we will get a pop-up window. Once the user enters the information into the pop-up box, the script is automatically called again with new variables $PHP_AUTH_USER (set to the username string entered), $PHP_AUTH_PASSWD (set to the password string entered), and $PHP_AUTH_TYPE. These variables will continue to be set by the browser on each request — one verification of identity per session.


In addition to redirection and authentication, you can use header() to explicitly set the expiration and caching behavior of your page, or send return status codes that tell the client whether whatever is returned should be considered a success or not.

Chief Programmabilities