PHP Redirect – How to do a PHP Redirect?

By Techblissonline Staff Updated on 20th December 2014 Filed Under: Tech Tips

Loading...

Are you looking for a way to redirect your PHP page? Earlier we covered a few basic redirection techniques like the HTTP Redirect, Javascript redirect and .htaccess redirect.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 “http://www.domain.com/redirect-to-new-page.php” 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.

<?php
Header( "HTTP/1.1 301 Moved Permanently" );
Header( "Location: http://www.domain.com/redirect-to-new-page.php" );
die();
?>

The above piece of code will permanently redirect (301 redirect) the PHP page to http://www.domain.com/redirect-to-new-page.php, where “redirect-to-new-page.php” is a php page on the domain “http://www.domain.com”. 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:

<?php
        ob_start();
        echo "Hello.";
        header("Location: http://www.domain.com/redirect-to-new-page.php");
        ob_flush();
    ?>

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

One Response to “PHP Redirect – How to do a PHP Redirect?”

  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

Go to Top