PHP redirects are useful as they allow you to transparently send a user to a different page. For example, you could want to redirect a user to the home page after they have successfully logged out. There is the option of using meta refresh or some Javascript in your markup to perform the redirection, but the process is smoother and more liquid when it is done on the server side.
Redirections happen when the server informs the browser (via the HTTP response) that the page has moved. This is done using a particular HTTP response code. We will be using a "302 Found" response from the server to demonstrate the redirection.
With PHP, we are able to manipulate some of the headers returned by the web server using the header function. This is how we will specify to the browser, as part of the HTTP response, that the page that was requested has moved.
The example below is a simple PHP script which performs a redirect:
<?php header('Location: http://www.example.com/new_page.php'); ?>
That's all there is to it. It you attempt to fetch a script containing that code in your web browser, you will notice that the address in your browser automatically changed to the address specified.
The header function MUST be called before the script sends and data to the user or else you WILL get an error!
Sometimes you may get an error like the one below:
Remember, ALL calls to the header function MUST be made before the script starts to output any data, that is, before any echo or print statements; even if they only print a single space.
The reason for this is simple. The way HTTP works is that the response headers are sent first and then content is sent directly after. If you were to start outputting some data from your script, the web server will generate the response headers and begin to transmit them and the data to the client's browser. If you attempt to modify the headers after that it will throw an error, and reasonably so, as the headers have long been sent to the user.
If possible, there should be no other code on a page that does a redirection and at the very least the header function should be as near to the top of the script as possible.
We hope this tutorial has been useful and that you have learnt the basics of using PHP to redirect to another page.