PHP Redirection

How to create an PHP redirection. What are the solutions ?

This post is a personal a translation of a french article on the "Comment ça marche.net" website. The english version is available on http://en.kioskea.net/faq/9296-php-redirect-to-another-page-redirect-header
(source in french: http://www.commentcamarche.net/faq/878-redirection-php-redirect-header)

Simple redirection

To redirect the visitor to another page (especially useful in a conditional loop), simply use the following code:

<?php
header('Location: /document/mypage.php');
?>

Relative / absolute path

Ideally, choose an absolute path from the root of the server (DOCUMENT_ROOT), the following format: 

<?php
header('Location: /document/mypage.php');
?>

If ever the target page is on another server, you include the full URL

<?php
header('Location: http://www.mywebsite.com/page/');
?>

Temporary / permanent redirections

By default, the examples presented above are temporary redirection. Which means in particular that search engines such as Google would not index them.

So if you want to notify search engines that the page A is now at location B, use the following code at the beginning of the PHP file for Page A:

<?
header('Status: 301 Moved Permanently', false, 301);
header('Location: /contents/page');
exit();
?>

This is a permanent redirection (Status: 301 Moved Permanently). So, if you type the first URL in Google (page A), it will give you the address as a result of the second (page B), demonstrating that Google understood the redirection.

Why exit()?

The PHP code after the call to header() function will be performed by the server. Even if the visitor has already left at the address specified in the redirection, the server will still work for nothing. Which means that in most cases you have to use the function exit() to make the server stop is job.