PHP Session Variables
When you move from one web page to another, information stored in normal variables is lost.
A session allows a website to store information about a user and use it across multiple pages.
Sessions can be used to:
- Remember if a user has logged in
- Store a user’s ID
- Remember items in a shopping basket
- Keep a user’s score across several pages
Starting a Session
Before using session variables, the session must be started:
<?php
session_start();
?>
session_start() should be placed at the top of the page before any HTML.
Every page that needs to access the session must include session_start().
Creating a Session Variable
Session variables are stored using $_SESSION.
For example:
$_SESSION["loggedIn"] = true;
This creates a session variable called loggedIn and gives it the value true.
Unlike a normal variable, this value can be accessed from other pages on the website.
Using Sessions for Login
A website could check a username and password:
$username = $_POST["username"];
$password = $_POST["password"];
if ($username == "admin" && $password == "pass123")
{
$_SESSION["loggedIn"] = true;
}
The session variable is only created when the correct login details are entered.
Checking a Session Variable
isset() can be used to check whether a session variable has been created:
if (isset($_SESSION["loggedIn"]))
{
echo "You are logged in.";
}
else
{
echo "You must login to view this page.";
}
In this example isset($_SESSION[“loggedIn”]) checks whether the loggedIn session variable exists.
This can be used to protect pages that should only be viewed by logged-in users.
Ending a Session
When a user logs out, the session can be ended.
session_start(); session_destroy();
session_start() accesses the user’s current session.
session_destroy() then destroys the session and the information stored in it.