Databases Reference
In-Depth Information
"Please select gift suggestions from the list to add to your shopping list!";
header("Location: list.php?message=" . urlencode($message));
exit;
We can use the
$_SESSION['username']
variable to determine whether the guest is log-
ged in and, if so, what their username is. Since we'd like to check that the user is
authorized to check each page, we can define a PHP function
logincheck( )
to verify
that the user is logged in, and redirect the user to the login page if they are attempting
to access a page without being logged in, or after their session has expired:
// Check if the user is logged in. If not, send them to the login
// page
function logincheck()
{
session_start();
if (empty($_SESSION["username"]))
{
// redirect to the login page
header("Location: index.php");
exit;
}
}
We call this function near the beginning of each script in our application to prevent
people from sidestepping the authentication process; we could include an error mes-
sage saying something like “You must log in to access that page.”
Logging the User Out
To end a user's session with our gift registry application, we can have a “log out” link
that calls the
logout.php
script. This script initializes the session and then destroys it.
It then redirects the browser to the application main page:
<?php
// Log out of the system by ending the session and load the main
// page
session_start();
session_destroy();
// Redirect to the main page
header("Location: index.php");
?>
As you can see, the script doesn't produce any HTML output. Instead, it uses the
header( )
function to send a
Location
header line to the browser. When the browser
receives this, it loads the specified web page—in this case, the
index.php
file in the same
directory as the
logout.php
script.