A session is a medium to keep visitor’s information (in variables) on the server to be used across subsequent pages. When a visitor access your web site he/she is assigned a unique id called session id. PHP session allows you to store data between requests in the $_SESSION superglobal array. Unlike a cookie, the information is not stored on the user’s computer.
Let's understand it with an example. When we work with any application, we take some actions. We open the application, do some changes in it, and then finally we close it. This is very much similar to Session. The computer knows who we are. It knows when we start the application and when we end.
But internet doesn't work in the same fassion. There is a problem on the internet: HTTP is stateless and doesn't maintain state. Because of this, the web server does not know who we are or what we do. This problem can be short out by using session variables. Session variables can store user's information an make avaiable across multiple pages unless the session is timeout. By default, session variables availabe until the user closes the browser.
To start a new session, you have to just call the PHP session_start() function. With the help of session_start() function, you can create a new session and generate a unique session ID for the user. You can use below PHP code example to starts a new session.
<?php
// Start the session
session_start();
Note: Please not that, session_start() function must be the very first line in your document, before you use any HTML tags.
You can store your data into the session in the form of key-value pairs with the help of PHP superglobal array $_SESSION[]. These data will be available during the session lifetime. Once session is timeout, these data will be lost. You can use below PHP code example to store data into the session.
<?php
// Start the session
session_start();
// Set session variables
$_SESSION["name"] = "w3techpoint.com";
$_SESSION["type"] = "web technologies learning resources";
How to get data from PHP Session?
You can retrieve your data from the session by passing session variable key to PHP superglobal array $_SESSION[]. You can use below PHP code example to retrieve data from the session.
<?php
// Start the session
session_start();
// Get session variables value
echo "Name is: " . $_SESSION["name"];
echo "Type is: " . $_SESSION["type"];
// Get all the session variables values
print_r($_SESSION);
To modify a session variable value, just overwrite it:
<?php
session_start();
$_SESSION['name'] = 'https://www.w3techpoint.com';
print_r($_SESSION);
<?php
session_start();
// To remove a session variables, use session_unset('variable_name'):
session_unset('name');
// To remove all global session variables, use session_unset():
session_unset();
// To destroy the whole session, use session_destroy():
session_destroy();
HAPPY LEARNING:)