PHP Session
HTTP is stateless: the server does not remember you from one page to the next. A session solves this problem. It stores data about a user on the server, like the user name after login, and it can be used on all pages of the website.
How sessions work
session_start()creates a session and gives it a unique id, or continues the existing one.- The id is saved in a cookie (named PHPSESSID) in the browser of the visitor.
- The data is saved on the server in the
$_SESSIONarray. - On the next page the browser sends the id back, so PHP finds the same data.
Start a session and store data
session_start() must be called at the top of every page that uses sessions, before any output.
<?php
// page1.php
session_start();
$_SESSION["username"] = "Robin";
$_SESSION["role"] = "student";
echo "Session data is saved.";
?>
Output:
Tutorials Class - Output Window
Session data is saved.
Read session data
<?php
// page2.php
session_start();
echo "Hello " . ($_SESSION["username"] ?? "Guest");
?>
Output:
After opening page1.php in the same browser
Hello Robin
To know the id of the current session see how to get the session id.
Change and remove session data
<?php
session_start();
$_SESSION["role"] = "teacher"; // change a value
unset($_SESSION["username"]); // remove one value
?>
Destroy a session (logout)
<?php
session_start();
$_SESSION = []; // remove all data
session_destroy(); // destroy the session
header("Location: login.php");
exit;
?>
Simple login example
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// In a real site check the password hash in the database
$ok = ($_POST["user"] === "admin" && $_POST["pass"] === "secret");
if ($ok) {
session_regenerate_id(true);
$_SESSION["logged_in"] = true;
header("Location: dashboard.php");
exit;
}
echo "Wrong user or password.";
}
?>
On every protected page check if (empty($_SESSION["logged_in"])) { header("Location: login.php"); exit; }. Never save plain passwords, see how to store passwords securely.
Session security and lifetime
- Call
session_regenerate_id(true)after login, so an attacker can not reuse an old id. - Set the cookie as
secure,httponlyandsamesite. See PHP Security Tips. - Session files are removed after some time without use. The default is 24 minutes (
session.gc_maxlifetime= 1440 seconds). - The session ends when you destroy it, and the cookie normally disappears when the browser is closed.
Note:
Sessions and cookies are different. A cookie stores data in the browser, a session stores it on the server. Read the difference between cookies and session.
Next chapter: PHP Cookies.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| Difference Between Cookies and Session |