PHP Sessions and Cookies Explained
HTTP requests are independent by default. Sessions and cookies provide ways to retain information between requests, but they serve different roles.
What Is a Cookie?
A cookie is a small piece of data stored by the browser and sent back to the server on matching requests. Cookies are often used for preferences or as a session identifier. Do not store passwords or sensitive secrets directly in cookies.
setcookie("theme", "dark", [
"expires" => time() + 86400 * 30,
"path" => "/",
"secure" => true,
"httponly" => true,
"samesite" => "Lax",
]);
The secure option should be enabled on HTTPS sites. httponly prevents JavaScript from reading the cookie, and samesite helps control cross-site cookie sending.
What Is a Session?
A PHP session stores data on the server and normally identifies the visitor through a session ID held in a cookie.
session_start();
$_SESSION["user_id"] = 42;
$_SESSION["role"] = "editor";
Call session_start() before sending output. Store only the information the application needs, and do not treat a session value as proof of authorization without checking the user's permissions.
Login Security
After successful authentication, regenerate the session ID to reduce session fixation risk.
session_start();
// After verifying the user's credentials:
session_regenerate_id(true);
$_SESSION["user_id"] = $userId;
Use HTTPS, configure secure cookie attributes, expire sessions appropriately, and destroy session data during logout. Protect state-changing requests against CSRF.
Sessions vs. Cookies
Cookies are stored by the browser and can persist across browser sessions. Session data is stored server-side and is usually associated with a session identifier. The right choice depends on the data, its sensitivity, and the required lifetime.
Conclusion
Sessions are useful for server-side state such as authenticated user IDs. Cookies are useful for small browser-managed values such as preferences. Secure configuration and authorization checks are essential for both.