PHP Session
PHP session variables are used to store information about a user session or to change the settings of a user session. Session variables hold information for a single user and are available across all pages of the application.
PHP Session Variables
When you operate an application on your computer, you open it, make some changes, and then close it. This is similar to a session. The computer knows who you are. It knows when you open and close the application. However, on the internet, problems arise: since HTTP addresses are stateless, web servers do not know who you are or what you have done.
PHP sessions solve this problem by storing user information on the server for later use (such as user name, purchased items, etc.). However, session information is temporary and will be deleted after the user leaves the website. If you need to store information permanently, you can store the data in a database.
The session mechanism works by creating a unique ID (UID) for each visitor and storing variables based on this UID. The UID is stored in a cookie or passed through a URL.
Starting a PHP Session
Before you can store user information in a PHP session, you must first start the session.
Note: The session_start() function must be placed before the <html>
tag:
Example
<?php session_start(); ?>
<html>
<body>
</body>
</html>
The above code will register the user's session with the server, allowing you to start saving user information and assign a UID for the user session.
Storing Session Variables
The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
Example
<?php
session_start();
// Store session data
$_SESSION['views'] = 1;
?>
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
</head>
<body>
<?php
// Retrieve session data
echo "Page views: " . $_SESSION['views'];
?>
</body>
</html>
Output:
Page views: 1
In the following example, we create a simple page-view counter. The isset() function checks if the "views" variable is set. If the "views" variable is set, we increment the counter. If "views" does not exist, we create the "views" variable and set it to 1:
Example
<?php
session_start();
if(isset($_SESSION['views']))
{
$_SESSION['views'] = $_SESSION['views'] + 1;
}
else
{
$_SESSION['views'] = 1;
}
echo "Page views: " . $_SESSION['views'];
?>
Destroying a Session
If you wish to delete some session data, you can use the unset() or session_destroy() function.
The unset() function is used to free a specified session variable:
Example
<?php
session_start();
if(isset($_SESSION['views']))
{
unset($_SESSION['views']);
}
?>
You can also completely destroy the session by calling the session_destroy() function:
Example
<?php
session_destroy();
?>
Note: session_destroy() will reset the session, and you will lose all stored session data.