PHP Sessions
Sessions let you store user data on the server across multiple page requests, identified by a unique session ID usually stored in a cookie on the client. Sessions are commonly used to keep users logged in as they navigate a site.
Unlike cookies, session data is stored on the server, making it more secure for sensitive information like user IDs or roles. Every page that uses sessions must call session_start() before any output is sent.
session_start();
$_SESSION["key"] = "value";Starting a session
session_start() must be called at the very top of every script that uses session data, before any HTML or whitespace is output.
Storing and destroying session data
Data is stored in the $_SESSION array, like $_SESSION["user"] = "Amy";. session_destroy() ends the session and clears all its data.
<?php
session_start();
$_SESSION["username"] = "Amy";
echo "Session started for " . $_SESSION["username"];
?>Session started for AmyThe username is stored in the session so it can be accessed on later pages.
<?php
session_start();
echo isset($_SESSION["username"]) ? $_SESSION["username"] : "Not logged in";
?>AmyOn a later page, the same session data is still available after calling session_start().
Key points
- session_start() must run before any output on every page using sessions.
- Session data is stored in the $_SESSION array.
- Sessions store data on the server, unlike cookies which store data on the client.
- session_destroy() ends a session and clears its data.
