Redirecting Users with HTTP Headers


Besides reading HTTP headers, you can also create your own HTTP headers to send back to the browser. Probably the most useful of these is the location header, which tells the user's browser where to go.

To create an HTTP header, use the header function. For instance, to create a redirection header that tells the browser where you want it to go, call header("Location: URL").

For example, we can display a set of three buttons that let the user navigate to one of the examples from the previous chapter: phpbuttons, phplists, or phptextarea. To do that, we'll use three different buttons, each in its own form, and we'll pass the name of the example in the button's VALUE attribute:

 <FORM NAME="form1" ACTION="phpredirect.php" METHOD="POST">     <INPUT TYPE="SUBMIT" NAME="Button" VALUE="phpbuttons"> </FORM> 

You can see the HTML for these three buttons in phpredirect.html, Example 6-5.

Example 6-5. Letting the user decide where to go, phpredirect.html
 <HTML>     <HEAD>         <TITLE>Redirecting the user</TITLE>     </HEAD>     <BODY>         <H1>Redirecting the user</H1>         Which script would you like to see?         <FORM NAME="form1" ACTION="phpredirect.php" METHOD="POST">             <INPUT TYPE="SUBMIT" NAME="Button" VALUE="phpbuttons">         </FORM>         <FORM NAME="form2" ACTION="phpredirect.php" METHOD="POST">             <INPUT TYPE="SUBMIT" NAME="Button" VALUE="phplistbox">         </FORM>         <FORM NAME="form3" ACTION="phpredirect.php" METHOD="POST">             <INPUT TYPE="SUBMIT" NAME="Button" VALUE="phptextarea">         </FORM>         </SCRIPT>     </BODY> </HTML> 

When the user clicks one of the buttons in this page, Figure 6-5, the name of his or her selection is passed back to our PHP script, phpredirect.php, Example 6-6.

Figure 6-5. Redirecting the user.


To perform the redirection, all our PHP script has to do is to use the header function, as you see in phpredirect.php, Example 6-6.

Example 6-6. Redirecting a browser, phpredirect.php
 <?php     $redirect = "Location: " . $_REQUEST['Button'] . ".html";     echo header($redirect); ?> 

For example, if you click the phplistbox button, you'll be redirected to the phplistbox example, as shown in Figure 6-6.

Figure 6-6. Navigating to the Lists example.


Redirecting is particularly good for creating hot spots in image maps, as here, where we're testing the mouse location and navigating to a new URL as required:

 <?php     if($REQUEST["imap_x"] > 50 && $REQUEST["imap_x"] < 70){          if($REQUEST["imap_y"] > 30 && $REQUEST["imap_y"] < 90){             $redirect = "Location: www.php.net";             echo header($redirect);         }     } ?> 



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net