How to do a HTTP Redirect in PHP?

Are you looking for a way to redirect your PHP page? Earlier we covered a few basic redirection techniques like the HTML Redirection, Javascript redirection and .htaccess redirection in Apache. We also covered a few techniques to carry out a server-side 301 redirect on apache and IIS servers.

This article will present a simple PHP script to set up a PHP redirect page.In PHP, you can make use of the header() function to redirect a PHP page to another web page. Replace “” with the URL to which you want to redirect, in the following piece of code and add it to any PHP page (PHP generated page) that you want to redirect.

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

The above piece of code will permanently redirect (301 redirect) the PHP page to, where “redirect-to-new-page.php” is a php page on the domain “”. Adding die() towards the end of the script ensures that no other piece of code is executed on the PHP page that you are redirecting. You may also use the exit function instead of die.

To do a temporary redirect (302 redirect), add “HTTP/1.1 302 Moved Temporarily” to the first header function, in the above script.

However, make sure that the above piece of code is called or executed before any actual output is sent i.e. Do not use any html tags, PHP echo or print functions before the above piece of code. otherwise you may get a warning message as below:

Warning: Cannot modify header information - headers already sent by

You can avoid the above warning message, even if you add an echo before the header function by using PHP output buffering as given in the example below:

        echo "Hello.";

That is all folks. Isn’t it easy to redirect a PHP Page?

One comment on “How to do a HTTP Redirect in PHP?

  1. WoW… I love this one, awesome solution… I have had problems with headers ever since and I could find a perfect solution when it had to be in the middle of HTML tags. – Thanks

Leave a Reply

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