Conversion tables A-K
  Conversion tables L-Z
  SPAM database query
  Reverse WHOIS utility
  North America area codes
  PHP Example forums

PHP example repository.

Web www.web-max.ca
Back to examples
Using the header() function in PHP.

The header() function allows you send a custom header command to the web browser.

The main thing to rememeber with the header function is that it must be the first thing that sends output in you script. If it is not, you will receive the "headers already sent" error. The output can include error messages or simply a blank line before your initial <?php statement.

One of the most useful function is the redirect. This will tell the browser to load a different page.

$site_url="www.google.ca"";
header("Location: http://$site_url");

One of the many handy uses for this is if you have a site and you wish to track "click outs". You create an link on your site to an internal page, and then use the redirect to forward the user on the external site by either passing the new site in the URL or by passing a reference to a database which store the site addresses ( after you have recorded the click ). For example:

<?php

// Assume this is local_page.php?redirect_to=1

// we have an array of sites

$sites = array("http://www.google.ca","http://www.staycanada.ca");

// Count the click using whatever method you want ...

$click_count[$redirect_to]++;

// Now redirect the end user

header("Location: {$sites[$redirect_to]}");

?>


The extension to this is the permanent redirect. This is the same as the above with the addition of the 301 header code. This tell the browser ( and Google, Yahoo etc ) that you have moved a page.

header("HTTP/1.1 301");
header("Location: $check");

Why would you do this? The first one is if you do not have direct access to your webserver and you have moved some PHP pages, this will allow you to redirect clients and search bots to your new pages with any penalty.

The second way that I use it is if I have created some dynamic pages which I have then converted to static pages. I can add some extra code to the dynamic page to check for the existance of a static version. If I find this other version I redirect the browser / bot to the other version:

<?php

// Lets assume we are in "/news.php?type=sport" or
// "/news.php?type=showbiz"
// and that we have decided we have enough "sport" or "showbiz " to
// create our own sport / showbiz pages

if(fileexists("{$type}.php))
{
    $new_location = "{$type}.php";
    header("HTTP/1.1 301");
    header("Location: {$new_location}");
}

?>