By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

PHP Redirect

Tutorial on how to perform simple redirection with PHP.

Edited: 2014-10-04 12:12

The PHP Redirect performed by sending the HTTP Location Header to the browser, which can be done with the PHP Header function. The location should be sent a long with the relevant HTTP status message – the type of redirect is controlled trough a separate header sent by PHP. Its important to get both the location header, and the status message right.

The below example deals with a 301 Permanent Redirect – permanent redirection is performed for pages that have moved, this is done so that search engines will automatically recognize them as having been moved.

if ($_SERVER['REQUEST_URI'] === '/my-old-page.php') {
  header("HTTP/1.1 301 Moved Permanently");
  header('Location: http://brugbart.com/');
  exit();
}

The $_SERVER['REQUEST_URI'] variable may not be the best way to perform your redirects, but it does give you a basic idea about how you can perform easily perform redirects.

The exit function placed on the last line, makes sure that any code coming afterwards, will not be run – you can combine this with an if, else check, for example to check if the page has been moved.

Redirecting Multiple Pages

The above example is not very suitable if you got a lot of pages that needs to be redirected – one way to redirect multiple pages, is to list them in an array first, and then loop trough this array.

Arrays can be constructed easily, one of the easiest ways is to do like below.

$OldPages[1] = 'Old-Page-1.php';
$OldPages[2] = 'Old-Page-2.php';
$OldPages[3] = 'Old-Page-3.php';
 // etc...

You would then create an array containing all the new locations.

$NewPages[1] = 'http://brugbart.com/New-Page-1';
$NewPages[2] = 'http://brugbart.com/New-Page-2';
$NewPages[3] = 'http://brugbart.com/New-Page-3';
 // etc...

These can then be checked for in our loop – the full code for this example, is provided below.

 // Old Locations
$OldPages[1] = 'Old-Page-1.php';
$OldPages[2] = 'Old-Page-2.php';
$OldPages[3] = 'Old-Page-3.php';
 // New Locations Below!
$NewPages[1] = 'http://brugbart.com/New-Page-1';
$NewPages[2] = 'http://brugbart.com/New-Page-2';
$NewPages[3] = 'http://brugbart.com/New-Page-3';

$MaxPages = count($OldPages);

$Counter = 1;
while ($Counter <= $MaxPages) {
  if ($_SERVER['REQUEST_URI'] === $OldPages["$Counter"]) {
  header("HTTP/1.1 301 Moved Permanently");
  header('Location: ' . $NewPages["$Counter"]);
  exit();
  }
++$Counter;
}

See also

  1. HTTP Response Codes
  2. Redirect from MySQL with PHP – Learn how to perform redirects from a database driven website.