11.6. Logging Users Out

After an authorized user completes his administrative tasks, he needs to be able to log out from the site. To enable this, all you need to do is unset $_SESSION['loggedin'], which hides the admin links and prevents any administrative actions from being performed until the user logs in again.

11.6.1. Adding a Log Out Link

You can simplify this process by adding a Log out link to your blog pages. This is as simple as adding an additional if block to index.php that displays a message notifying a user that she is logged in, as well as a link that allows her to log out.

You can keep the link visible by placing it right under the menu. In index.php, add the code in bold between the menu and the entries container:

<body>

    <h1> Simple Blog Application </h1>
    <ul id="menu">
        <li><a href="/simple_blog/blog/">Blog</a></li>
        <li><a href="/simple_blog/about/">About the Author</a></li>
    </ul>

<?php if(isset($_SESSION['loggedin']) && $_SESSION['loggedin']==1): ?>
    <p id="control_panel">
        You are logged in!
        <a href="/simple_blog/inc/update.inc.php?action=logout">Log
            out</a>.
    </p>
<?php endif; ?>

    <div id="entries">

Navigate to http://localhost/simple_blog/ while logged in to see the new notification and Log out link (see Figure 11-7).

Figure 11.7. When logged in, you now see a notification and a link to log out.

11.6.2. Modifying update.inc.php to Log Out Users

The code you created in the last step means the Log out link will send your user to update.inc.php and use the GET method to pass a variable called action that is set to logout.

At the bottom of update.inc.php, add one more else if block that checks whether $_GET['action'] is set to logout; if so, use the session_destroy() function to destroy $_SESSION['loggedin'] and any other session variables, which reverts the user back to an unauthorized state and once again hides the administrative links and actions. From here, you simply send the user back out to the default page.

Insert the following code in bold into update.inc.php, just above the last else block:

// If the user has chosen to log out, process it here
else if($_GET['action'] == 'logout')
{
    session_destroy();
    header('Location: ../'),
    exit;
}

else
{
    header('Location: ../'),
    exit;
}

?>

You can test this code by clicking the Log out link on any page. Doing so takes you back to the main page and hides the administrative links (see Figure 11-8).

Figure 11.8. Logging out hides the administrative links again.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.249.174