Logging out is the simplest part of the process. The logout.php page starts off as a standard script, including the configuration 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 configuration 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 actually 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.
The complete logout.php is:
1 <?php 2 require ('./includes/config.inc.php'); 3 redirect_invalid_user(); 4 $_SESSION = array(); 5 session_destroy(); 6 setcookie (session_name(), '', time()-300); 7 $page_title = 'Logout'; 8 include ('./includes/header.html'); 9 echo '<h3>Logged Out</h3><p>Thank you for visiting. You are now logged out. Please come back soon!</p>'; 10 require (MYSQL); 11 include ('./includes/footer.html'); 12 ?>
Figure 4.14 shows the result.