Sessions and cookies
Keep a signed-in state on the server and use cookies for small preferences.
What you will be able to do
- Call session_start before reading or writing $_SESSION.
- Store the user id in the session, not the password.
- Regenerate the session id after sign-in.
- Set cookie flags: Secure, HttpOnly and SameSite.
In plain English
A session stores data on the server and gives the browser only an opaque id cookie. That is the right place for a user id or a cart. Cookies are for small, non-sensitive preferences the browser may send back on every request.
<?php
session_start();
$_SESSION['visits'] = ($_SESSION['visits'] ?? 0) + 1;
setcookie('theme', 'dark', [
'expires' => time() + 60 * 60 * 24 * 30,
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
echo 'Visits: ' . $_SESSION['visits'];Your turn
EasyCount visits
Increment a session counter and print the current visit number.
PHP · starter
session_start();Check your understanding before moving on.
Knowledge checkQuestion 1
Where is session data stored by default?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.