PHP
Summary - Sessions
Build a simple login system with session_start, $_SESSION and destroy.
Summary - Sessions
In this group you learned the five pillars of sessions: start with session_start(), write with $_SESSION, read with isset(), remove one variable with unset() and close everything with session_destroy().
Combined, they form a login/logout system: on a successful login you store an id in the session, check it on protected pages, and clean up on logout.
The last step is a mini app that puts the whole flow together.
Combine the login system
A login system has three parts: login (verify, write to session), check (use isset) and logout (unset + destroy).
On login, if the username and password match, $_SESSION['user'] is written. Every protected page starts with if (!isset($_SESSION['user'])); if undefined, it returns to the login page.
The logout page calls unset($_SESSION['user']) and session_destroy(), then redirects to the login page.
Exercise Summary - Mini login and logout
Call session_start(). Set $_SESSION['user'] to 'Alex' and $_SESSION['role'] to 'admin'. echo Hello and the username. Then call unset($_SESSION['user']). With if/else, check isset($_SESSION['user']): if defined print yes, otherwise gone.
Show example solution
Call session_start, assign user and role, echo Hello, unset($_SESSION['user']), then if(isset(...)) prints yes/gone.
Example solution:
<?php
// Start the session, greet, then remove the session variable
session_start();
$_SESSION['user'] = 'Alex';
$_SESSION['role'] = 'admin';
echo "Hello " . $_SESSION['user'] . "\n";
unset($_SESSION['user']);
if (isset($_SESSION['user'])) {
echo "yes\n";
} else {
echo "gone\n";
}
Test yourself
-
Match the five pillars of the session system
- session_start()
- Starts the session
- $_SESSION
- Stores the data
- isset()
- Checks a key
- unset()
- Removes one key
- session_destroy()
- Destroys the session
-
What is the correct logout sequence?
- unset($_SESSION['user']) then session_destroy()
- session_destroy() then unset()
- Only session_destroy()
- Only unset($_SESSION)
Show answer
unset($_SESSION['user']) then session_destroy() — Correct. First the user variable is unset, then the whole session is destroyed.
-
Remove the user on logout
<?php
session_start();
$_SESSION['user'] = 'Alex';
echo 'Hello ' . $_SESSION['user'];
____
$_SESSION['log'] = ['action' => 'logout'];
var_dump(isset($_SESSION['user']));
Show answer
<?php
session_start();
$_SESSION['user'] = 'Alex';
echo 'Hello ' . $_SESSION['user'];
unset($_SESSION['user']);
$_SESSION['log'] = ['action' => 'logout'];
var_dump(isset($_SESSION['user']));
Next lesson: Creating cookies with setcookie()