Ok finally i managed to write a new article after about a month ( actually i do not even want to think when i wrote last good article for you). Anyway today short article on using headers to redirect vistors to other pages on your site or external site.

To do this you need only one function
header($header, $replace, $http_response_code);

First argument $header is a header itself. We want to use header to redirect visitors so in our case we will use something like “Location: URL” where URL is obviously an url of a page to which you want to redirect visitor. It can be full url (http://some-random-url.com/pages/page.html) or relative URL (pages/page.html)

Boolean argument $replace indicates whatever previous similar headers should be replace or not. By default this value is set to true, so all similar headers are replaced.

The last argument is HTTP response code. While $replace argument maybe not so useful, $http_response_code might come handy, because it allows to select method of redirection. Full list of HTTP response codes can be found at Wikipedia: List of HTTP status codes. We will be interested in 3xx response codes as they are responsible for redirections.

  • 301 – Moved Permanently. This and all future requests should be directed to the given URI.
  • 302 – Moved Temporarily. Usually browsers use it as 303 redirection
  • 303 – See Other. Resource you are looking for can be found under different URL
  • 307 – Temporary Redirect

It maybe a little bit confusing if you are new to this, so remember that only first argument in header function is required, others are optional.

Examples

Here are some valid PHP redirections:

header("Location: http://google.com");
header("Location: pages/page.php");
header("Location: http://google.com", true, 303);
header("Location: http://google.com", true);

Remember also that headers MUST be sent before any output is started. There are no exceptions from this rule, in fact you cannot even sent a blank line to the output, executing code like this:

text
<?php header("Location: ditio.net"); ?>

will throw warning “Cannot add/modify header information – headers already sent by…“. To avoid such situation you can use output buffering or just make sure that nothing was sent to the client.