Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
This chapter is from the book

HTTP Headers

HTTP (HyperText Transfer Protocol) is the technology at the heart of the World Wide Web because it defines the way clients and servers can communicate (in layman's terms). When a browser requests a Web page, it receives a series of HTTP headers in return.

PHP's built-in function header() can be used to take advantage of this protocol. The most common example of this will be demonstrated here, when the header() function will be used to redirect the Web browser from the current page to another. However, in Chapter 10, "Extended Topics," you'll see how to use header() to affect page caching, and in Chapter 8, "Security," you'll use it to perform HTTP authentication.

To use header() to redirect the Web browser, type

header ("Location: http://www.url.com/page.php");

Because this should be the last thing to occur on the current page (since the browser will soon be leaving it), this line would normally be followed by a call to the exit() function, which stops execution of the current script.

The absolutely critical thing to remember about the header() function is that it must be called before anything is sent to the Web browser. This includes HTML or even blank spaces. If your code has any echo() or print() statements, blank lines outside of PHP tags, or includes files that do either of the above, you'll see an error message like that in Figure 3.20 .

03fig20.gif

Figure 3.20 The headers already sent error message is all too common for PHP programmers.

To avoid this, use the headers_sent() function, which checks whether or not data has been sent to the Web browser.

if (!headers_sent()) {
   header ("Location: http://www.url.com/page.php");
   exit();
} else {
   echo 'Wanted to redirect you but I could not do it! ';
}

I'll modify the current registration script so that the user is redirected to a thank-you page upon successful registration. To do so will require that I restructure the page to ensure that no text is sent to the browser before I call header().

To use the header() function:

  1. Open register.php (refer to Script 3.12) in your text editor.
  2. Move the entire isset() conditional to the very top of the page, above the include line (Script 3.13).
    if (isset($_POST['submit'])) {
    
    If all of the conditions are passed, the user will be redirected. For this reason, I don't want to automatically include the header file (and its HTML), so I place my conditional as the first thing in the script.
  3. Create a new $message variable.
    $message = NULL;
    
    The $message variable will be used in lieu of the echo() statements when a condition is not passed. I must do this so that I can later display the messages in the context of the HTML template (if I printed the errors as they occurred, they'd appear before the top part of the template generated by the header file).
  4. Rewrite the conditionals, replacing each echo() statement with $message .=.
    if (strlen($_POST['name']) > 0) {
       $name = TRUE;
    } else {
       $name = FALSE;
       $message .= '<p>You forgot to enter your name!</p>';
    }
    if (strlen($_POST['email']) > 0) {
       $email = TRUE;
    } else {
       $email = FALSE;
       $message .= '<p>You forgot to enter your email address!</p>';
    }
    if (strlen($_POST['username']) > 0) {
       $username = TRUE;
    } else {
       $username = FALSE;
       $message .= '<p>You forgot to enter your user name!</p>';
    }
    if (strlen($_POST['password1']) > 0) {
       if ($_POST['password1'] == $_POST['password2']) {
          $password = TRUE;
       } else {
          $password = FALSE;
          $message .= '<p>Your password did not match the confirmed password!</p>';
       }
    } else {
       $password = FALSE;
       $message .= '<p>You forgot to enter your password!</p>';
    }
    
    The $message variable is being built up as one long string containing all of the accumulated error messages.
  5. Add the header() function to the registration process.
    if ($name && $email && $username && $password) {
       $body = "Thank you for registering with our site!\nYour username is
       '{$_POST['username']}' and your password is '{$_POST['password1']}'.\n\nSincerely,\nUs";
       mail ($_POST['email'], 'Thank you for registering!', $body, 'From: admin@site.com');
       header ('Location: thankyou.php');
       exit();
    } else {
       $message .= '<p>Please try again.</p>';
    }
    
    The header() function will send the user to a thank-you page if everything went OK. Then the script is exited, which means that everything else in the script will not be executed.
  6. Change the submit conditional.
    }
    
    This version of the script will not use an else with the submit conditional as it previously had. Thus I change the line here and remove the closing brace before the include('./footer.inc') line.
  7. Include the HTML header.
    $page_title = 'Register!';
    include ('./header.inc');
    
    After the main conditional and once the header() function would have been called, it's now safe to use the included file.
  8. Print out any error messages.
    if (isset($message)) {
       echo '<font color="red">', $message, '</font>';
    }
    
    Web users will be seeing this page under two circumstances: once when they first arrive and again if they fail to fill out the form completely. Under this second situation, the $message variable will have a value (of what they forgot) and it will be printed here, above the form.
  9. Keep the rest of the file as is and save your changes.

Example 3.13. The header() function can redirect the user to another page.

1   <?php # Script 3.13 - register.php
2
3   if (isset($_POST['submit'])) { // Handle the form.
4
5       $message = NULL;
6
7      // Check for a name.
8      if (strlen($_POST['name']) > 0) {
9          $name = TRUE;
10     } else {
11         $name = FALSE;
12         $message .= '<p>You forgot to enter your name!</p>';
13     }
14
15     // Check for an email address.
16     if (strlen($_POST['email']) > 0) {
17         $email = TRUE;
18     } else {
19         $email = FALSE;
20         $message .= '<p>You forgot to enter your email address!</p>';
21     }
22
23     // Check for a username.
24     if (strlen($_POST['username']) > 0) {
25         $username = TRUE;
26     } else {
27         $username = FALSE;
28         $message .= '<p>You forgot to enter your user name!</p>';
29     }
30
31     // Check for a password and match against the confirmed password.
32     if (strlen($_POST['password1']) > 0) {
33         if ($_POST['password1'] == $_POST['password2']) {
34             $password = TRUE;
35         } else {
36             $password = FALSE;
37             $message .= '<p>Your password did not match the confirmed password!</p>';
38         }
39     } else {
40         $password = FALSE;
41         $message .= '<p>You forgot to enter your password!</p>';
42     }
43
44     if ($name && $email && $username && $password) { // If everything's okayOK.
45         // Register the user.
46
47         // Send an email.
48         $body = "Thank you for registering with our site!\nYour username is
 '{$_POST['username']}' and your password is '{$_POST['password1']}'.\n\nSincerely,\nUs";
49         mail ($_POST['email'], 'Thank you for registering!', $body, 'From: admin@site
.com');
50
51         header ('Location: thankyou.php');

   52         exit();
53     } else {
54         $message .= '<p>Please try again.</p>';
55     }
56
57  }
58
59  // Set the page title and include the HTML header.
60  $page_title = 'Register!';
61  include ('./header.inc');
62
63  // Print the error message if there is one.
64  if (isset($message)) {
65      echo '<font color="red">', $message, '</font>';
66  }
67  ?>
68
69  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
70  <fieldset><legend>Enter your information in the form below:</legend>
71
72  <p><b>Name:</b> <input type="text" name="name" size="20" maxlength="40" /></p>
73
74  <p><b>Email Address:</b> <input type="text" name="email" size="40" maxlength="60" /></p>
75
76  <p><b>User Name:</b> <input type="text" name="username" size="20" maxlength="40"/></p>
77
78  <p><b>Password:</b> <input type="password" name="password1" size="20" maxlength="40" /></p>
79
80  <p><b>Confirm Password:</b> <input type="password" name="password2" size="20" 
maxlength="40" /></p>
81  </fieldset>
82
83  <div align="center"><input type="submit" name="submit" value="Submit Information" /></div>
84
85  </form><!-- End of Form -->
86
87  <?php
88  include ('./footer.inc'); // Include the HTML footer.
89  ?>

Now I'll put together a quick thank-you page.

To create a thank-you page:

  1. Create a new PHP document in your text editor (Script 3.14).
    <?php # Script 3.14 - thankyou.php
    $page_title = 'Thank You!';
    include ('./header.inc');
    echo '<p>Thank you for registering!</p>';
    include ('./footer.inc');
    ?>
    
  2. Save the script as thankyou.php, upload to your Web server along with the modified register.php, and test in your Web browser ( Figures 3.21 and 3.22 ).
    03fig21.gif

    Figure 3.21 If the user filled out the form completely, he or she will be redirected to this page.

    03fig22.gif

    Figure 3.22 The page now reports on any skipped fields and the form is displayed again.

Example 3.14. The user will be sent to this thank-you page upon successful registration.

1   <?php # Script 3.14 - thankyou.php
2
3   // Set the page title and include the HTML header.
4   $page_title = 'Thank You!';
5   include ('./header.inc');
6
7   echo '<p>Thank you for registering!</p>';
8
9   include ('./footer.inc'); // Include the HTML footer.
10  ?>"
  • + Share This
  • 🔖 Save To Your Account