3.5. Protecting Your Web Pages

When the user successfully logs in or registers through the login Web page displayed by the script Login_reg.php, the Web page shown in Figure 3-2 is displayed.

This Web page script is part of your protected Web site that you do not want users to see without logging in. The Web pages in your protected Web site, or section of your Web site, are no different than any other Web pages. You just want to restrict them to members who are logged in. To do this, you start a session and check whether the user is logged in at the top of every page.

Figure 3-2. The Web page that displays when the user successfully logs in.

The script that displays the Web page in Figure 3-2 is displayed by the script SecretPage.php shown in Listing 3-4.

Example 3.4. The Script That Runs When the User Successfully Logs In
<?php
 /* File: SecretPage.php
  * Desc: Displays a welcome page when the user
  *       successfully logs in or registers.
  */
   session_start();                                                     →6
   if(@$_SESSION['auth'] != "yes")                               →7
   {
      header("Location: Login_reg.php");
      exit();
   }                                                                    →11
   echo "<head><title>Secret Page</title></head>
         <body>";
   echo "<p style='text-align: center; font-size: 1.5em;
            font-weight: bold; margin-top: 1em'>
            The User ID, {$_SESSION['logname']}, has
            successfully logged in</p>";
?>
</body></html>

This script is protected so that a user can't access it unless he or she is logged in. Lines 6–11 protect ...

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.