Posted by : senan Wednesday, February 12, 2014

Sessions are used to store information which can be used through-out the application for the entire time the user is logged in or running the application. Each time a user visits your website, you can create a session for that user to store information pertaining to that user.
Unlike other applications, in web applications, all the stored variables and objects are not globally available throughout all pages (unless sent through POST or GET methods to the next page), so to tackle this problem sessions are utilized.
A usage of sessions would be for example, storing products in a shopping cart. On your favorite merchant site, when you, the user, clicks on "add to shopping cart", the product information is then stored in a session (using session variables) which is then available on the server for later use for the entire the time you browse the website.


Sessions in PHP

In PHP, information is stored in session variables. Now lets learn how we create a session in PHP
Before you can store any information in session variables, you must first start up the session using the session_start() function. See below.
<?php 
session_start(); 
?>

<html>
<body>

</body>
</html>
When you start a session a unique session id (PHPSESSID) for each visitor/user is created. You can access the session id using the PHP predefined constant PHPSESSID.
The code above starts a session for the user on the server, and assign a session id for that user's session.
Note: The session_start() function must appear BEFORE the <html> tag

Storing information in a session

To store information is a session variable, you must use the predefined session variable $_SESSION.
Now, as an example, lets store user's name and their favorite color in a session. To do so you would do the following.
<?php 
session_start(); 

$_SESSION["username"] = "johny";
$_SESSION["color"] = "blue";

?>

Retrieving stored session information

Retrieving stored session information is really easy. You can access the stored session information on any page without doing anything extra.
<?php 
session_start(); 

echo $_SESSION["username"];
echo "<br/>";
echo $_SESSION["color"];

?>

Output

Johny
blue

Destroying/deleting session information

Remember sessions are destroyed automatically after user leaves your website or closes the browser, but if you wish to clear a session variable yourself, you can simple use the unset() function to clean the session variable.
<?php 
session_start();

unset($_SESSION["username"]);

unset($_SESSION["color"]);

?>
To completely destroy all session variables in one go, you can use the session_destroy() function.
<?php 
session_destroy();
?>

Leave a Reply

Subscribe to Posts | Subscribe to Comments

- Copyright © Learning Programming Language - Skyblue - Powered by Blogger - Designed by Johanes Djogan -