How to create a 301 redirect with PHP?

Creating a 301 redirect as part of the server configuration is always the best solution. But if you only need to build a local redirection, only from one specific file of your server, it can be useful to make it in a scripting language such as PHP, rather than configuring the whole server for an exceptional behaviour.

This page describes the few steps you'll need to follow in order to set up a 301 redirect using PHP language. In fact, the main steps of this process only consist of a two lines code you'll have to paste on top of the file you need to redirect. That's all.

Defining the 301 code and the target address.
As PHP is a server side language, it can easily compute some data even before any answer has been sent to the client browser from the server. Using this behaviour, and some adequate commands, it's then easy to dynamically write a new header for a request and define it as a 301.

To achieve this, first open the file from which you want to set up the redirection. This file must, of course, be a PHP file in order to be able to execute PHP code on your server. Then, copy the following code, as the very first lines of your PHP file, and replacing the by the real destination address of your 301.

Header( "HTTP/1.1 301 Moved Permanently" );
Header( "Location:" );

In the PHP language, Header command is used to redefine the header of the server's answer, and so can be used to define a 301 redirect. This way, the first information your client will receive is the relocation command. Obeying to the redirection code, it will not keep in consideration any line of the following page.

Dynamically defining the redirection target.
If the Header must be the first instruction to be sent to the client, it's not necessarly the first one to be executed by the server. Using PHP redirection, you are free to use any command you need before the Header instruction, as long as you don't send any data to the client browser.

You can then easily imagine that the target address of the redirection is defined following attributes present in the original page address, session's values or any database entry. Storing this new address in a PHP variable is then easy, and reusing it in the Header command is a matter of a single line modification:

Header( "Location: $NewAddress" );