Logging out is the simplest part of the process. The logout.php page starts off as a standard script, including the config file, the header, the MySQL connection, and the footer. Only logged-in users should be able to access this page, though, so a call to redirect_invalid_user() is included just after the config file is defined.
To wipe out the session, three steps are required. First, clear out the $_SESSION array that represents the variables available to this script:
$_SESSION = array();
Next, the session_destroy() function removes the data stored on the server:
Finally, modify the session cookie in the user’s browser so it no longer has a record of the session ID:
setcookie(session_name(), '', time()-300);
That line sends a cookie with the same session name, but no value (no session ID) and an expiration of five minutes ago.
Here’s the complete logout.php:
<?php require('./includes/config.inc.php'); redirect_invalid_user(); $_SESSION = array(); session_destroy(); setcookie (session_name(), '', time()-300); require(MYSQL); $page_title = 'Logout'; include('./includes/header.html'); echo '<h1>Logged Out</h1><p>Thank you for visiting. You are now logged out. Please come back soon!</p>'; include('./includes/footer.html'); ?>
Figure 4.10 shows the result.