faqts : Computers : Programming : Languages : PHP : Common Problems : Redirects

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

448 of 575 people (78%) answered Yes
Recently 6 of 10 people (60%) answered Yes

Entry

How do I redirect http page, e.g. http://from.com to http://to.com in PHP code

Apr 29th, 2001 18:44
Philip Olson, Tsu-Hua Wang,


This is very easy with PHP :
  <?php
    $to = 'http://www.example.com';
    header('Location: '. $to); 
    exit;
  ?>
HTML can do it just as well, with a meta tag, like so :
  <META HTTP-EQUIV="Refresh" Content= "0; URL=<?php echo $to; ?>">
Javascript can also do it but there is no reason to as javascript can 
easily be disabled within a browser, some don't even support it.  That 
said, this works via javascript :
  <script language="JavaScript">
      parent.location.href='<?php echo $to; ?>';
  </script>
Using the PHP header() method has cost newbies a frustrating question 
or two as the following will NOT work :
  echo 'foo';
  header('Location: foo.php');
A warning similar to the following will result :
  foo
  Warning: Cannot add header information - headers already sent by
            (output started at /home/http/foo/bar.php:4) 
           in /home/http/foo/bar.php on line 5
Output cannot happen before such a header call.  Note that it works 
perfectly as running, for example, a conditional as the following 
causes no output (or error) beforehand :
  if ($foo == 'home') {
    header('Location: home.php');
  }
Our first example used:  exit;  as it terminates the script after 
redirecting.  Without such a termination, the script will continue to 
run ... even after the redirection.  See the manual for further 
information and examples :
  header -- Send a raw HTTP header   :
  http://www.php.net/manual/en/function.header.php
  exit   -- Terminate current script :
  http://www.php.net/manual/en/function.exit.php