Using Sessions


Sessions:These are groups of variables that are stored on the server but relate only to the current user. To ensure that the right variables are applied to the right users, PHP saves a cookie in the users’ web browsers to uniquely identify them.


This cookie has meaning only to the web server and cannot be used to ascertain any information about a user sessions provide a solid way of keeping track of your users.


Starting a session requires calling the PHP function session_start before any HTML has been output, similarly to how cookies are sent during header exchanges.


Then, to begin saving session variables, you just assign them as part of the $_SESSION array, like this:

$_SESSION['variable'] = $value;


They can then be read back just as easily in later program runs, like this:

$variable = $_SESSION['variable'];


Now assume that you have an application that always needs access to the username,

password, first name, and last name of each user, as stored in the table users, which you should have created a little earlier. So let’s further modify authenticate.php from


Setting a session after successful authentication

<?php //authenticate2.php
 require_once 'login.php';
 $connection =
 new mysqli($db_hostname, $db_username, $db_password, $db_database);
 if ($connection->connect_error) die($connection->connect_error);
 if (isset($_SERVER['PHP_AUTH_USER']) &&
 isset($_SERVER['PHP_AUTH_PW']))
 {
 $un_temp =
mysql_entities_fix_string($connection, $_SERVER['PHP_AUTH_USER']);
 $pw_temp = mysql_entities_fix_string($connection, $_SERVER['PHP_AUTH_PW']);
 $query = "SELECT * FROM users WHERE username='$un_temp'";
 $result = $connection->query($query);
 if (!$result) die($connection->error);
elseif ($result->num_rows)
 {
 $row = $result->fetch_array(MYSQLI_NUM);
 $result->close();
 $salt1 = "qm&h*";
$salt2 = "pg!@";
 $token = hash('ripemd128', "$salt1$pw_temp$salt2");
 if ($token == $row[3])
 {
 session_start();
 $_SESSION['username'] = $un_temp;
 $_SESSION['password'] = $pw_temp;
 $_SESSION['forename'] = $row[0];
 $_SESSION['surname'] = $row[1];
 echo "$row[0] $row[1] : Hi $row[0],
 you are now logged in as '$row[2]'";
 die ("<p><a href=continue.php>Click here to continue</a></p>");
 }
 else die("Invalid username/password combination");
 }
 else die("Invalid username/password combination");
 }
 else
 {
 header('WWW-Authenticate: Basic realm="Restricted Section"');
 header('HTTP/1.0 401 Unauthorized');
 die ("Please enter your username and password");
 }
 $connection->close();
 function mysql_entities_fix_string($connection, $string)
 {
 return htmlentities(mysql_fix_string($connection, $string));
 }
 function mysql_fix_string($connection, $string)
 {
 if (get_magic_quotes_gpc()) $string = stripslashes($string);
 return $connection->real_escape_string($string);
 }
?>




One other addition to the program is the “Click here to continue” link with a destination URL of continue.php. This will be used to illustrate how the session will transfer to another program or PHP web page. So create continue.php by typing/copying the program in Example  below and saving it.


Retrieving session variables

<?php // continue.php
 session_start();
 if (isset($_SESSION['username']))
 {
$username = $_SESSION['username'];
 $password = $_SESSION['password'];
 $forename = $_SESSION['forename'];
 $surname = $_SESSION['surname'];
 echo "Welcome back $forename.<br>
 Your full name is $forename $surname.<br>
 Your username is '$username'
 and your password is '$password'.";
 }
 else echo "Please <a href='authenticate2.php'>click here</a> to log in.";
?>


Now you are ready to call up authenticate2.php into your browser. Enter a username of bsmith and password of mysecret (or pjones and acrobat) when prompted, and click the link to load in continue.php. 


Explanation of the code:


Sessions neatly confine to a single program the extensive code required to authenticate and log in a user. Once a user has been authenticated, and you have created a session, your program code becomes very simple indeed. You need only to call up session_start and look up any variables to which you need access from $_SESSION.

A quick test of whether $_SESSION['username'] has a value is enough to let you know that the current user is authenticated, because session variables are stored on the server (unlike cookies, which are stored on the web browser)

and can therefore be trusted.


If $_SESSION['username'] has not been assigned a value, no session is active, so the

last line of code in Example above directs users to the login page at authenticate2.php.


Ending a Session


When the time comes to end a session, usually when a user requests to log out from your site, you can use the session_destroy function in association, as in

 The example provides a useful function for totally destroying a session, logging a user out, and unsetting all session variables.

A handy function to destroy a session and its data

<?php
 function destroy_session_and_data()
 {
 session_start();
 $_SESSION = array();
 setcookie(session_name(), '', time() - 2592000, '/');
 session_destroy();
 }
?>
To see this in action, you could modify continue.php as in Example below:
 Retrieving session variables and then destroying the session
<?php
 session_start();
 if (isset($_SESSION['username']))
 {
 $username = $_SESSION['username'];
 $password = $_SESSION['password'];
 $forename = $_SESSION['forename'];
 $surname = $_SESSION['surname'];
 destroy_session_and_data();
 echo "Welcome back $forename.<br>
 Your full name is $forename $surname.<br>
 Your username is '$username'
 and your password is '$password'.";
 }
 else echo "Please <a href='authenticate2.php'>click here</a> to log in.";
 function destroy_session_and_data()
 {
 $_SESSION = array();
 setcookie(session_name(), '', time() - 2592000, '/');
 session_destroy();
 }
?>




Explanation of the code:

The first time you navigate from authenticate2.php to continue.php, it will display all the session variables. But, because of the call to destroy_session_and_data, if you

then click your browser’s Reload button, the session will have been destroyed and you’ll be prompted to return to the login page.


At this point,we have learnt enough on PHP and MYSQL we are going to learn on Javascript ,keep updated on our latest publish by following us.