A session is just the time a person spends on a website. PHP has a session management system that allows us to keep track of what a visitor is doing, what he or she likes, what he or she wants, and so on, even after the user signs off. The concept is similar to that of cookies in that the goal is to keep state.
The session_start() function
Starting a session requires calling the PHP function session_start before any HTML has been output, similarly to how cookies are sent during header exchanges. Then, to begin saving session variables, you just assign them as part of the $_SESSION
array.
<?php
session_start(); // starts a session
Important: The function, session_start()
, must be called at the beginning of the page. This function starts by checking if there is already a session via session ID. If there is no session yet, it starts a new one.
The $_SESSION variable
The $_SESSION
variable is an associative array where the session data are stored. Below is an example of a typical use of the variable.
<?php
session_start(); // starts a session
?>
<html>
<head></head>
<body>
<h2>Visitor Tracker</h2>
<?php
if ( ! isset($_SESSION)) {
$_SESSION[visitor_count] = 0;
} else {
$_SESSION[visitor_count]++;
}
echo "You are visitor number". $_SESSION['visitor_count']. ".<br />";
echo "The session id is: ",session_id();
?>
</body>
</html>
Storing and Accessing $_SESSION variable data
Since the $_SESSION
variable is an associative array, data can be accessed and/or stored as key-value pairs. Below is a simple example of storing and accessing the session data via the $_SESSION
variable.
<?php
session_start(); // starts the session
$_SESSION["user"] = "admin";
$_SESSION["password"] = "password";
echo "Username: " . $_SESSION["user"] . "<br>";
echo "Password: " . $_SESSION["password"] . "<br>";
Ending a Session
PHP really has no way to know when the user has left a session, so it provides several functions to help you control when to end a session. To end a session, you need to delete the session variables and destroy the session itself. This can be done using the session_unset()
and session_destroy()
functions.
<?php
session_start(); // starts the session
// Storing session data
$_SESSION["user"] = "admin";
$_SESSION["password"] = "password";
echo 'Username: ' . $_SESSION["user"];
echo '<br>';
echo 'Password: ' . $_SESSION["password"];
session_unset(); // removes session variables
session_destroy(); // destroys the session
// try to access the session variables after session is destroyed
echo '<br>' . 'Accessing the session variables after session is destroyed';
echo '<br>';
echo 'Username: ' . $_SESSION["user"];
echo '<br>';
echo 'Password: ' . $_SESSION["password"];