...

Understanding Session in PHP - Create, Read, Update, Delete

Sessions are one of the most important topics for PHP developers to grip and in this post I am going to describe the basic concepts regarding sessions. Before anything else lets read the definition of session from w3schools:

“A session is a way to store information (in variables) to be used across multiple pages.”

They also mentioned “Unlike a cookie, the information is not stored on the users computer”

Sessions are used for storing data that you want to use on various pages again and again. In PHP, dealing with sessions is quite easy and once you get the understanding of session you can easily tackle with situations where sessions are needed like for storing a customer’s products in cart before checkout and many more.

Basics of sessions include starting a session, registering session variables, reading the session variables, modifying session variables and destroying those variables.

Start Session

The first and most important part of session is initializing it at the very start of PHP file where sessions are to be used. This is achieved by a method of PHP known as “session_start()”. Just write this method on the very beginning of file after opening the PHP tag and you are good to go.

Register variable (Create)

PHP handles all the session variables using global variable $_SESSION (You can think of it as an associative array where you store values against keys). If you want to register a session variable you can easily do it like

$_SESSION[`key`] = value;

For example if you want to save the name of user who is logged in and this name is going to be used again and again at various pages than you can easily set it as a session variable like

$_SESSION[`fullName`] = “Abdul Rehman”;

Reading variable

Reading or getting the value of specific session variable is also super easy and you can just use $_SESSION[`key`] to get the value saved against that key. For example if you want to get and print the name of user than you can do it like

echo $_SESSION[`fullName`];

Modify variable

Modifying a session variable is also a simple task. You just have to overwrite the value against specific variable like

$_SESSION[`fullName`] = “Abdullah”;

This line of code will update the full name of user from “Abdul Rehman” to “Abdullah”

Delete variable and full session

Deleting a single session variable is achieved by the unset method of PHP. For deleting single variable you have to write:

unset($_SESSION[key]);

For removing all the variables you have to use session_unset() method like:

session_unset();

In this way you can use sessions in your web app for any case you face. I have used PHP just to give you the understanding of sessions and its use. Happy Coding :)

If you have any question in mind or want to suggest something than feel free to contact me.