When we open an application on the computer, we do some work on it, the computer knows exactly who we are. But on the internet, the webserver does not know who you are and what you do, because the HTTP address does not maintain state. In order to overcome this server maintains the session or state for every user till the time user is on the website.
PHP $_SESSION is a variable that stores temporary information about the current user. For example, if you are browsing the website the only way to identify the current user is, by using a session. PHP $_SESSION allows the server to store information about the user, which we can get later on any page within the website.
How does PHP Session work?
PHP $_SESSION makes a unique id for each user, that unique ids are stored in the browser in the form of cookies and the session data is stored in the server, no matter how many users are accessing the website. PHP sessions can accurately identify each user and serve them with the required data. PHP sessions are safe to use since its data gets stored on the server and there is no way to hijack the server session data.
Starting PHP Session
We use session_start() function. to start PHP session. Put the code in the top of the page
<?php session_start(); // starts PHP session ?>
Store & Retrieve Session variables
Once the session is started, we can store multiple values in PHP $_SESSION.
$_SESSION is a global variable and can be accessed anywhere on the website by just putting session_start() function on top of the page.
<?php // starts PHP session session_start(); //store a session variable $_SESSION["name"] = "atcodex"; //storing array variables $_SESSION["arr"] = array('name' => 'atcodex', 'url' => 'https://atcodex.com', 'type'=> 'blog'); ?>
When we have stored the variable in the session, we can retrieve the value anywhere within the website.
<?php // start or resume PHP session session_start(); //retrieve and output stored session variable echo $_SESSION["name"]; //retrieve array vars print_r($_SESSION["arr"]); ?>
Removing or Destroying PHP $_SESSIONS
We can remove session variables using unset(). It is used to remove particular variable from the session.
<?php //removes variable called name unset($_SESSION["name"]); ?>
To destroy everything in the current session we use session_destroy(). The function will destroy all session values.
<?php //destroy everything session_destroy(); ?>