Session Syntax in PHP
<?php
session_start(); // used to create a PHP session or resume the current one
session_destroy(); // used to destroy all data registered to a session
session_unset(); // used to free all session variables currently registered
isset(); // determines if a variable is set and is not NULL
$_SESSION; // superglobal array used to store session variables
// example: $_SESSION['username'] = 'JohnDoe';
?>
Starting a new session
<?php
session_start();
?>
Storing Session Data
<?php
session_start(); // used to create a PHP session or resume the current one
$_SESSION['username'] = 'JohnDoe';
$_SESSION['email'] = 'johndoe@email.com';
$_SESSION['role'] = 'admin';
Reading Session Data
<?php
session_start();
$username = $_SESSION['username']; // Assigning session to variable
$email = $_SESSION['email'];
$role = $_SESSION['role'];
if (isset($_SESSION['username'])) { // check if the username session is assigned
echo "Welcome, " . $username . "!<br>"; // display the sessions
echo "Email: " . $email . "<br>";
echo "Role: " . $role . "<br>";
} else {
echo "No active session found. Please log in.";
}
Destroy a PHP Session
<?php
session_unset(); // Free all session variables
session_destroy(); // Destroy the session