Objective. Students implement PHP session management to maintain login state across pages and explain the security difference between storing data in sessions versus cookies
This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.
VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.
When a user visits a PHP web application, the server needs a way to remember who they are from one page to the next. HTTP is a stateless protocol, meaning each request is independent and the server has no built-in memory of previous requests. PHP sessions solve this problem.
When you call `session_start()` at the top of a PHP script, PHP either creates a new session or resumes an existing one. The session data is stored on the server in a temporary file (or database, depending on configuration). PHP generates a unique identifier called the session ID and sends it to the browser as a cookie named `PHPSESSID`. Every time the browser makes a new request, it sends that cookie back, and PHP uses the ID to retrieve the correct session data.
You store and read session data through the superglobal array `$_SESSION`:
```php
<?php
session_start();
$_SESSION['username'] = 'jsmith';
$_SESSION['logged_in'] = true;
```
To end a session and clear all its data — which is what you do when a user logs out — call `session_destroy()` after unsetting the session array:
```php
<?php
session_start();
$_SESSION = [];
session_destroy();
header('Location: login.php');
exit;
```
Always call `exit` after a `header()` redirect so no further code runs.
Cookies are small pieces of data the server sends to the browser, which the browser stores locally on the user's device. You set a cookie in PHP with `setcookie()`:
```php
setcookie('theme', 'dark', time() + 86400, '/', '', true, true);
```
The parameters control the name, value, expiration time, path, domain, whether to send only over HTTPS (`Secure` flag), and whether JavaScript can access it (`HttpOnly` flag).
| Feature | Sessions | Cookies |
|---|---|---|
| Data stored | Server | User's browser |
| User can tamper | No (server-side) | Yes (client-side) |
| Lifespan | Ends when browser closes (default) | Set by expiration time |
| Accessible to JavaScript | No (only the ID cookie) | Yes, unless HttpOnly flag is set |
Because session data lives on the server, users cannot easily alter it. Cookie values can be read and modified by the user or, in some attacks, by malicious scripts. Never store sensitive data such as a user ID, role, or balance in a plain cookie. Store it in `$_SESSION` instead, and keep only the session ID in the browser.
A basic login flow has three pages:
1. login.php — shows a form; on POST, validates credentials; on success, sets `$_SESSION['logged_in']` and redirects.
2. protected.php — checks `$_SESSION['logged_in']`; redirects to login if not set.
3. logout.php — destroys the session and redirects to login.
Every page that uses `$_SESSION` must begin with `session_start()` before any output.
Never store plain-text passwords. PHP provides two built-in functions for password security:
```php
// When creating an account (store this in the database):
$hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
// When logging in (fetch $storedHash from the database first):
if (password_verify($_POST['password'], $storedHash)) {
// credentials are correct
}
```
The hash is a long string that looks like random characters. Never echo, log, or display the hash in output. Doing so does not immediately expose the password, but it gives attackers a target to crack offline.
Open DevTools (F12 in most browsers), go to the Application tab, and look under Cookies for your local site. You will see `PHPSESSID` listed there. Notice it has no readable value that corresponds to your username — it is just a random token. Any cookies you set manually with `setcookie()` also appear here, and you can see their expiration, path, and flags. This inspection exercise demonstrates concretely why session data is more secure than cookie data for sensitive information.
Answer each question, then check it. Nothing is recorded; this is your own practice.
A free tech program — complimentary, as our commitment to get America working. Help us build VoTechWorks. Tell us what works, what doesn’t, and what you want to learn.