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
Category:Sessions
Level:Beginner

Bookmark PHP session tutorial



Bookmark and Share

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:

Code:
  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.
Code:
  1. if (isset($_SESSION['username'])){
  2. echo "User : ".$_SESSION['username'];
  3. } else {
  4. echo "Set the username";
  5. $_SESSION['username'] = 'John';
  6. }
  7.  





Previous Step of PHP session tutorial


Tags: php sessions, php, session, session handling



Follow phpf1 on Twitter




F1 Site Family
AJAX F1
CSS F1
Database F1
HTML F1
Java F1
JavaScript F1
PHP F1

Total time: 0.0185