Backup of the original page by Frank Boumphrey:

www.hypermedic.com/php/index.htm

Please consult the original if still available.


Redirection

[Index]

Redirecting pages is very simple in PHP. We simply use the header() function to post a new Location parameter in the HTTP headers.

Redirecting a Page

header() is used to send raw HTTP headers. See the HTTP/1.1 specification http://www.w3.org/Protocols/rfc2616/rfc2616 for more information on HTTP headers. The "Location" header not only sends this header back to the browser, but it also returns a REDIRECT (302) status code to the browser. The following will redirect a page to the given address. Note that this must be done right at the top of the page, before any HTML script is written.

<?
      header("Location: http://localhost/phpcourse/apps/ck_register.php");
      // exit the page to make sure nothing further is added to the headers.
      exit;
?>

Note that an absolute path must be provided for the location. It is possible to build this on the fly as follows, using SERVER variables and the dirname() function.:

//the relative path
$relative_url="apps/ck_register.php";

//build the absolute path
header("Location: http://".$HTTP_SERVER_VARS['HTTP_HOST']
                      ."/".dirname($HTTP_SERVER_VARS['PHP_SELF'])
                      ."/".$relative_url);

Conditionally Redirecting a Page

The page must be redirected before any of the other headers are written, but provided we put this at the top o the page, it will work.

 <?
    if($pet=="dog")
      {
       header("Location: http://localhost/phpcourse/apps/dogs.htm");
       // exit the page to make sure nothing further is added to the headers.
       exit;
       }
     elseif($pet=="cat")
	   {
	    header("Location: http://localhost/phpcourse/apps/cats.htm");
	    // exit the page to make sure nothing further is added to the headers.
	    exit;
       }
     else
	   {
	    header("Location: http://localhost/phpcourse/apps/petrocks.htm");
	    // exit the page to make sure nothing further is added to the headers.
	    exit;
       }
 ?>

İFrank Boumphrey 2001