How to Automatically Redirect a Page in PHP

To redirect a page to another page during PHP processing, simply use the header function demonstrated below:

<?php
   header("Location: http://www.victorchen.info");
?>

Whenever this script is reached, the page will automatically redirect to http://www.victorchen.info.

  1. The header function must occur before any page output. This includes page outputs originating from include() or require() functions. Additionally, keep an eye out for blank lines before the header function is executed.
  2. The URL does not need to be a full url (http://www.victorchen.info). It can alternatively be “../index.html”.

The below example will not work because there is an output of “This will not work” before the header() function is called.

<?php
   header("Location: http://www.victorchen.info");
?>

This example will also not work because the text “This will not work” is placed in an php echo command.

<?php
   echo "This will not work";
   header("Location: http://www.victorchen.info");
?>

This next example shows how having a hidden space before the first php command will also not work. Please note the first line of the example below is empty! To see this highlight the code below and see the first character is a blank!

<?php
   header("Location: http://www.victorchen.info");
?>

Lastly, the following code below will work. The string “This will work” is placed after the redirect.

<?php
   header("Location: http://www.victorchen.info");
   echo "This will work";
?>

Please note that the string “This will work” will never actually execute in this scenario, as the header function will trigger the page to first redirect. Simply placing an if statement around the header function allows toggling of when the header function is executed.

Share and Enjoy:
  • Digg
  • DotNetKicks
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Live
  • MySpace
  • Netvibes
  • Reddit
  • StumbleUpon
You can leave a response, or trackback from your own site.

3 Responses to “How to Automatically Redirect a Page in PHP”

  1. Dan says:

    A safer way is:

    http://danltn.com/bin/57q.phps

    Using if(!headers_sent()) means it will only output if there has been no output so far, safer than simply supressing errors.

    Also, use an exit() or die(); after your code, otherwise the rest can easily be read by a user, and it could be confidential. Redirecting doesn’t stop output.

    Dan

  2. Valintino says:

    Hello, Your site is great. abra2 [url=http://www.abra3.com]abra3[/url] http://www.abra1.com [URL]http://www.abra4.com[/URL] Regards, Valiintino Guxxi

  3. jen says:

    Does anyone know how I can use a PHP redirect while still calling my statcounter code to log the hit to the redirect page?

Leave a Reply