PHP session tutorial - Clean and destroy session

Home - Tutorials - Sessions

In this tutorial I will show you how to work with sessions in PHP. You will learn how to transfer information between pages.

Tutorial info:

Name:PHP session tutorial
Total steps:5

Bookmark PHP session tutorial

Step 5 - Clean and destroy session

PHP session tutorial

Sometimes it is important to remove a session variable or destroy the complete session. Such mechanism is used for example during a user logs out from a site.

To remove a variable from a session is quite easy. You just have to call the unset() function to do this. Now you can extend our example code to unset the username as follows:

  1. if (isset($_SESSION['username'])){
  2. echo "User : ".$_SESSION['username'];
  3. unset($_SESSION['username']);
  4. } else {
  5. echo "Set the username";
  6. $_SESSION['username'] = 'John';
  7. }
The result of this code is similar to a login/logout system. If the user is logged in then we display the name than log him off. In the next execution we log him in again.

You can use the session_destroy() function if you want to remove all session data, but be careful with it.
  1. if (isset($_SESSION['username'])){
  2. echo "User : ".$_SESSION['username'];
  3. } else {
  4. echo "Set the username";
  5. $_SESSION['username'] = 'John';
  6. }

Previous Step of PHP session tutorial

Tags: php sessions, php, session, session handling

Follow phpf1 on Twitter

F1 Site Family
Java F1
JavaScript F1

Total time: 0.1466