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)
To redirect the visitor to another page (especially useful in a conditional loop), simply use the following code:
Relative / absolute path
Ideally, choose an absolute path from the root of the server (DOCUMENT_ROOT), the following format:
If ever the target page is on another server, you include the full URL:
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);
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.
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.