Wednesday, March 11, 2015

PHP Sessions

With PHP we have the possibility to create user sessions, with which data can be saved globally and for later access. One example could be a login function: The user enters his name and password once at the beginning, if this matches, he is logged in, so a session is created, in other scripts now can be checked whether the user is logged in and what he is allowed to do.
Every session has a unique ID, which is saved by default in a cookie, so the user is still logged in on the next visit / call. But the ID can also be appended to the URL. Next the ID in theory arbitrary many variables can be saved in the session.

If we want to use a PHP session we use in the code the function session_start(). Via $_SESSION['x'] we then can access variable x. Useful is further the function isset(), with which we can check whether some variable is already existing and not NULL. This way we can also check, whether already a session for the current user exists.

The following script creates on the first call by a user the session variable "visited" and writes something to it. Then in later calls by the same user (or by someone who owns the right cookie) the function isset(visited) returns true and the script recognizes the user:

<?php
session_start();

if(!isset($_SESSION['visited']))
{
   echo "First time!";
   $_SESSION['visited'] = "something";

else
{
     echo "Visited";
}
?>

You find the script on http://bloggeroliver.bplaced.net/PHPExamples/session.php.
In a later post I will describe a login system, here I want to finish with some at least more useful example than the one above, a user counter:

<?php
session_start();

if(!isset($_SESSION['counter']))
{
   $_SESSION['counter'] = 0;
}  
$_SESSION['counter']++;

echo $_SESSION['counter'];
?>

To destroy a session, we have to delete all session data and then terminate the session:

$_SESSION = array();
session_destroy();

But also this does not suffice yet, because the cookie still exists and can be used. Therefore we also have to delete the cookie, which I do not want to describe here.
Because, on the one hand the session is terminated automatically if we have created it using a browser and close the browser. And on the other hand this blog focusses on C# and we will later use sessions in C#. Thus we can also delete the cookie there.

No comments:

Post a Comment