• 2010-05-03
  •   PHP

The ability to redirect URLs in PHP can be very handy. A common use of redirects is when a page has become obsolete and you would like to redirect the user to a more current one. Affiliate marketers use URL redirection to point to their products. This way when the product they are marketing is no longer sold they point their URLs to another similar product and keep their landing pages functional. There are two ways to redirect URLs in PHP:

The first is using PHP's built in header function. The syntax is:

<?php
header('Location: http://codehill.com/');
?>

The advantage of redirecting using the header function is its the fastest, because you only send an HTTP header containing the location to go to. Its disadvantage is it has to be the first thing to send. If there is any text, even a space or new line, before the opening PHP tag an error will occur.

The second way is to write the meta refresh tag using PHP. The meta refresh tag looks like this:

<META HTTP-EQUIV="Refresh" Content="0; URL=http://codehill.com">

And you could just print it using PHP:

<?php 
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=http://codehill.com">'; 
?>

This line of code could be anywhere in the page, not just at the top like the header function.This makes it much more flexable, because you could check for a condition anywhere in the page or display a formated HTML page for a few seconds or minutes before redirecting the visitor.