Home » Tech Tips

PHP Redirect – How to do a PHP Redirect?

 August 22, 2009 No Comment

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 artile 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.

<?
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”. Also 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.

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?

Filed under: Tech Tips

Leave a Reply