Logging out

Where are we?

This chapter is about restricting access to the admin section of a Web site.

You know how to add a log in page, store log in data in sessions, and check it in every admin page.

The only thing left to do is let the user log out.

This lesson’s goals

Learn:

  • How to add a log out link on the admin menu.
  • The log out page gets rid of the session data.

The admin menu (admin/index.php) has a log out link. The user clicks it to log out:

Log out link

Figure 1. Log out link

Here’s the HTML that makes the link:

<a href="log-out.php">Log out</a>

Just a simple link. But that does the log out page do?

Logging out

The code we wrote to restrict access uses session data. The log out code gets rid of it.

Here’s the code for log-out.php.

<?php
//Log out
//Path from this page to the site root.
$path_to_root = '..';
session_start();
//Kill all the the session variables.
$_SESSION = array();
//Kill the session itself.
session_destroy();
//Back to the log in page.
header("location:$path_to_root/admin/log-in.php");
exit();
?>

Figure 2. log-out.php

Line 7 erases the session data, including the log in flag and all permissions information. Line 9 destroys the session itself. Line 11 jumps back to the log in page.

That’s it!

W00f!

Renata
Renata

The erases all of the session data, right?

Kieran
Kieran

Yes.

Renata
Renata

Is there session data you might not want to erase?

Kieran
Kieran

Ooo, good question!

You can use the session to store data about anything. Like the winner of the Tokyo dog show.

In the code we’ve been looking at, we only used the session to store information about log in and permission. So erasing it all makes sense.

But if you’re using the session to store other information as well, you might want to just erase the log in and permission stuff, like this:

$_SESSION['logged in'] = '';
$_SESSION['permission add'] = '';
$_SESSION['permission edit'] = '';
$_SESSION['permission delete'] = '';

Summary

  • There’s a log out link on the admin menu.
  • The log out page gets rid of the session data.

What now?

Now for some exercises.


How to...

Lessons

User login

Log in problems? Try here


Dogs