Introduction to PHP - Session Variables Part 2

Guest Posts Paolo Nikko Nuñal

From the previous tutorial we have taught you how to store variables in session. This time around you are going to learn on how you can modify a session and use it on trapping specific pages that require admin restrictions.

Lets say for example, you have a control panel page. And you have already stored the usertype of a user in a session variable. You can easily redirect them by checking the usertype.

<?php
   session_start();
   if($_SESSION['user_type'] != 'ADMIN')
   {
      header("Location: not_allwoed.php");
   }
}
?>


From the code above, we managed to retrieve the $SESSION['usertype'] and check if the user is an "ADMIN" or not. If the usertype is not equivalent to "ADMIN" it will automatically be redirected to another page.

This is a great example on how you can protect other pages from being viewed from unauthorized users. These include admin pages, control panels and the like.

Another example we would be modifying $
SESSION variables with the use of the unset() function. The unset() function basically 'unsets' or remove a variable from the $_SESSION array. This is good if you want an element to be erased. You can do this like.

<?php
   session_start();
   unset($_SESSION['username']); // DESTROYS 'username'
   session_unset(); // DESTROYS the entire  session variables but not the session itself.
}
?>


Lastly, if you want to completely destroy a session like say a new user wants to log-in. You can do so, with the sessiondestroy(); This would destroy the session and all of its variables. This is useful if you have a log-out screen and you want to completely erase all of the sessionvariables associated with the log-in.