How to redirect using PHP

Using PHPs header() function you can easily redirect to an URL of your choice by passing a simple parameter. In the below example we will redirect the user to http://www.geekpedia.com.

<?php
header("Location: http://www.geekpedia.com");
?>

As you can see, we pass as a parameter a string starting with “Location: ” followed by the actual URL to which we wish to redirect the user. The URL can either be an absolute location or a path relative to the server.

It is very important to know how the header() function works in order for you to use it properly. The header() function tells the PHP server to change the header sent to the client (the browser) and load a different location – the one followed by the “Location: ” statement. However, if any output is sent to the client before the header function is executed, different headers will already be sent, and the new one sent by header() will fail. The redirection will not happen and an error will be returned: “Header already sent” – and it will show you (the line) were the output first started.
That is why it is important to use the header() function in PHP only when you don’t plan in showing any output on the page in which the redirection takes place. If you’d like to show output while the client gets redirected, along with a time delay redirect, you should then look for other methods of doing that, such as Javascript redirection and HTML meta redirection.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top