🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Web & Software Development › PHP and Python Web Programming › Lesson 5
TEC-WEB46-03 · Lesson 5 · 11.5 clock hours · demo

PHP Sessions, Cookies, and Authentication Basics

Objective. Students implement PHP session management to maintain login state across pages and explain the security difference between storing data in sessions versus cookies

⚠ Pending professional review

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.

What Are PHP Sessions?

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.

What Are Cookies?

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).

Sessions vs. Cookies: The Key Security Difference

| 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.

Building a Login Flow

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.

Storing Passwords Safely with Hashing

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.

Security Practices for This Lesson

Using Browser Developer Tools

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.

Key terms9

session_start()PHP function that must be called before any output on every page that uses sessions; it creates a new session or resumes an existing one based on the session cookie sent by the browser.
$_SESSIONPHP superglobal associative array used to store and retrieve server-side session data across multiple page requests for the same user.
session_destroy()PHP function that deletes all session data stored on the server and invalidates the session; used during logout after clearing the $_SESSION array.
PHPSESSIDThe default name of the cookie PHP sends to the browser to track which server-side session belongs to that user; it contains only a random ID, not the actual session data.
password_hash()PHP function that produces a secure one-way hash of a plain-text password using bcrypt or the current recommended algorithm, automatically including a salt.
password_verify()PHP function that checks whether a plain-text password matches a hash created by password_hash(); returns true on match, false otherwise.
HttpOnly flagA cookie attribute that prevents client-side JavaScript from accessing the cookie, reducing the risk of the cookie being stolen through cross-site scripting (XSS) attacks.
session_regenerate_id()PHP function called after a successful login to assign a new session ID to the current session, preventing session fixation attacks where an attacker pre-sets a known session ID.
setcookie()PHP function used to create a cookie that the browser stores on the client device; accepts parameters for name, value, expiration, path, domain, Secure flag, and HttpOnly flag.
In class: Instructor demonstrates session_start(), $_SESSION assignment, and session_destroy() by building a simple login/logout flow; students replicate the demo in their own environment and add a protected page that redirects unauthenticated users · Students inspect browser developer tools to view the session cookie (PHPSESSID) and a manually set cookie; they record the difference in storage location, lifespan, and accessibility, and write a short comparison in their lab log · Students harden their login page by adding password_hash() and password_verify() for credential storage and checking; they test with correct and incorrect passwords and confirm the hash is never displayed in output or logs
Materials: PHP manual (sessions, password functions), browser developer tools, VS Code, local PHP environment, student lab log template
Check: Students demonstrate a working login/logout flow with a protected page; password is stored as a hash and verified correctly; lab log comparison of sessions vs. cookies is accurate — pass requires all three features working and lab log entry graded complete

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

CompTIA ITF+ — Software and Application Concepts
1. Where is PHP session data stored by default?
CompTIA ITF+ — Software and Application Concepts
2. A developer calls session_start() on a page but sees the error 'Cannot modify header information — headers already sent.' What is the most likely cause?
PCEP Python / General Security Concepts (ITF+)
3. Which PHP function should be used to verify a user's login password against a stored hash?
CompTIA ITF+ — Security Concepts
4. A student stores the user's account balance in a browser cookie and reads it back on checkout. What is the primary security risk?
CompTIA Linux+ — Security
5. What is the purpose of calling session_regenerate_id(true) immediately after a successful login?
CompTIA ITF+ — Security Concepts
6. Which cookie flag prevents JavaScript running on the page from reading the cookie's value?
CompTIA ITF+ — Software and Application Concepts
7. A protected page should redirect unauthenticated users to login.php. Which code block correctly implements this check?
CompTIA ITF+ — Security Concepts
8. When inspecting cookies in browser developer tools, a student sees the PHPSESSID cookie. What does the value of this cookie contain?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.