A session is a way to store information in variables. A PHP session stores data on the server rather than user's computer. In a session based environment, every user is identified through a unique number called session identifier or SID. The session IDs are randomly generated by the PHP engine which is almost impossible to guess.
Starting a PHP Session
Before you can store any information in session variables, you have to start the session. It will create a new session and generate a unique session ID for the user.
// Starting session
You must call the session_start() function at the beginning of the page before any HTML tags. If the session is already started, it sets up the session variables and if doesn't, it starts a new session by creating a new session ID.
You call session_start() on every page and subsequently have access to all the items in the $_SESSION array. You can then set, update, and delete variables from the session like any other array by using the reserved array $_SESSION.
Storing Session Data
You can store all your session data in the $_SESSION superglobal array. The stored data can be accessed during lifetime of a session.
// Storing session data
$_SESSION["firstname"] = "John";
$_SESSION["lastname"] = "Doe";
Accessing Session Data
The stored data can be accessed during lifetime of a session. You can access the session data from any other page on the same web domain.
// Accessing session data
echo 'Hi, ' . $_SESSION["firstname"] . ' ' . $_SESSION["lastname"];
Destroying a Session
If you want to remove certain session data, you can unset the corresponding key.
// Removing session data
To destroy a session completely,
// Destroying session
Every PHP session has a timeout value (duration measured in seconds) which determines how long a session should remain alive in the absence of any user activity.