🧩 Module 10: Sessions, Cookies, and Authentication
Objective: Learn how to store user information across multiple pages using sessions and cookies,
and build a secure login/logout system to manage authentication.
🔹 1. What Are Sessions?
A session stores temporary data about a user while they’re browsing your website.
✅ Example uses:
- Keep users logged in
- Store shopping cart data
- Track preferences
PHP identifies each user with a unique session ID stored on the server.
🧩 How to Start a Session
<?php
session_start(); // Must be at the top of the page
$_SESSION["username"] = "Yogi";
echo "Session started for " . $_SESSION["username"];
?>
✅ $_SESSION works like an array that persists across pages.
🧩 Accessing Session Data on Another Page
<?php
session_start();
echo "Welcome back, " . $_SESSION["username"];
?>
✅ The user’s name carries over — even on a different page.
🧩 Destroying a Session
<?php
session_start();
session_unset(); // Removes session variables
session_destroy(); // Destroys session
echo "Session ended.";
?>
🧠 This is typically used for logging users out.
🔹 2. What Are Cookies?
A cookie is a small text file stored on the user’s computer.
It can persist long after they leave your site — great for “Remember Me” features or saving preferences.
🧩 Setting a Cookie
<?php
setcookie("username", "Yogi", time() + (86400 * 7)); // 7 days
echo "Cookie set!";
?>
✅ time() + (86400 * 7) means it expires in 7 days.
🧩 Accessing a Cookie
<?php
if (isset($_COOKIE["username"])) {
echo "Welcome back, " . $_COOKIE["username"];
} else {
echo "Hello, new visitor!";
}
?>
🧩 Deleting a Cookie
<?php
setcookie("username", "", time() - 3600); // Past time = deleted
echo "Cookie removed.";
?>
🔹 3. Sessions vs Cookies
| Feature | Session | Cookie |
|---|---|---|
| Stored On | Server | User’s browser |
| Lifespan | Until browser closes (or manually destroyed) | Until expiration date |
| Security | More secure (hidden) | Less secure (user can view/edit) |
| Use Case | Login systems, carts | Preferences, “Remember Me” |
🧠 Tip: Use sessions for sensitive data; cookies for convenience.
🔹 4. Building a Simple Login System
Let’s build a small authentication workflow.
Step 1: login.php
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = $_POST["password"];
// Dummy credentials
if ($username == "admin" && $password == "1234") {
$_SESSION["user"] = $username;
header("Location: dashboard.php");
exit;
} else {
$error = "Invalid credentials!";
}
}
?>
<h2>StreetGeek Login</h2>
<form method="POST" action="">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" value="Login">
</form>
<?php if (isset($error)) echo "<p style='color:red;'>$error</p>"; ?>
✅ Submitting correct credentials takes you to dashboard.php.
Step 2: dashboard.php
<?php
session_start();
if (!isset($_SESSION["user"])) {
header("Location: login.php");
exit;
}
?>
<h2>Welcome, <?php echo $_SESSION["user"]; ?>!</h2>
<p>This is your dashboard.</p>
<a href="logout.php">Logout</a>
✅ Only accessible when logged in.
Step 3: logout.php
<?php
session_start();
session_destroy();
header("Location: login.php");
exit;
?>
✅ Logs out the user and clears the session.
🔹 5. Adding “Remember Me” Using Cookies
In login.php, modify the form handling section:
if ($username == "admin" && $password == "1234") {
$_SESSION["user"] = $username;
if (!empty($_POST["remember"])) {
setcookie("username", $username, time() + (86400 * 7)); // 1 week
}
header("Location: dashboard.php");
exit;
}
And in the login form:
<input type="checkbox" name="remember"> Remember Me
Now, if they check the box, their name persists via cookie.
✅ When they revisit login.php, you can auto-fill the username:
<input type="text" name="username"
value="<?php echo $_COOKIE["username"] ?? ''; ?>">
🔹 6. Security Considerations
- Never store raw passwords in sessions or cookies.
- Always hash passwords using
password_hash(). - Regenerate session IDs after login:
session_regenerate_id(true); - Use HTTPS to secure cookie data transmission.
- Always sanitize input (
htmlspecialchars()orfilter_input()).
🧩 Hands-On Practice
Exercise 1: Create and Access Session
session-demo.php:
<?php
session_start();
$_SESSION["academy"] = "StreetGeek Academy";
echo "Session set!";
?>
Then open session-check.php:
<?php
session_start();
echo "Welcome to " . $_SESSION["academy"];
?>
✅ Displays the session value from another page.
Exercise 2: Cookie Demo
cookie-demo.php:
<?php
setcookie("student", "Yogi", time() + 3600);
echo "Cookie set!";
?>
Then cookie-check.php:
<?php
if (isset($_COOKIE["student"])) {
echo "Welcome back, " . $_COOKIE["student"];
}
?>
Exercise 3: Simple Login
Create login.php, dashboard.php, logout.php using examples above.
✅ Test logging in/out and see how the session persists.
🎯 Mini Project – Secure Member Login System
Goal: Build a complete login/logout flow using sessions, cookies, and input validation.
Steps:
- Create a file
login-system.php. - Use this code:
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = htmlspecialchars($_POST["username"]);
$password = htmlspecialchars($_POST["password"]);
// Basic validation
if ($username == "admin" && $password == "1234") {
$_SESSION["user"] = $username;
session_regenerate_id(true);
if (!empty($_POST["remember"])) {
setcookie("user", $username, time() + (86400 * 7));
}
header("Location: member.php");
exit;
} else {
$error = "Invalid username or password!";
}
}
?>
<h2>Member Login</h2>
<form method="POST" action="">
Username: <input type="text" name="username"
value="<?php echo $_COOKIE["user"] ?? ''; ?>"><br>
Password: <input type="password" name="password"><br>
<input type="checkbox" name="remember"> Remember Me<br>
<input type="submit" value="Login">
</form>
<?php if (isset($error)) echo "<p style='color:red;'>$error</p>"; ?>
Create member.php:
<?php
session_start();
if (!isset($_SESSION["user"])) {
header("Location: login-system.php");
exit;
}
?>
<h3>Welcome, <?php echo $_SESSION["user"]; ?>!</h3>
<a href="logout.php">Logout</a>
Create logout.php:
<?php
session_start();
session_destroy();
setcookie("user", "", time() - 3600);
header("Location: login-system.php");
exit;
?>
✅ You now have a functional session + cookie-based authentication system.
🧾 Module 10 Quiz
| # | Question | Options | Correct |
|---|---|---|---|
| 1 | What function starts a session? | a) session_init() · b) session_start() · c) start_session() | b |
| 2 | Where are cookies stored? | a) Server · b) Browser · c) Database | b |
| 3 | Which function deletes a cookie? | a) cookie_unset() · b) setcookie() with past time · c) delete_cookie() | b |
| 4 | What is stored in $_SESSION? |
a) User preferences · b) Server-side variables · c) Page title | b |
| 5 | Which command regenerates a secure session ID? | a) session_refresh() · b) session_regenerate_id(true) · c) session_reset() | b |
💪 Challenge Task – Protected Dashboard System
Objective: Expand your login project into a real-world protected dashboard app.
Requirements:
- Login form with username & password validation
- Session storage for logged-in users
- Dashboard page accessible only if session is active
- Logout button that clears both session & cookie
- “Remember Me” feature that uses cookies for 7-day login persistence
✅ When a user revisits the site:
- If session exists → show dashboard
- If session doesn’t exist but cookie exists → auto-login
- Otherwise → show login page
🧾 Submission Checklist
- ✅
session-demo.php→ works across pages - ✅
cookie-demo.php→ sets and retrieves cookie - ✅
login.php+dashboard.php+logout.php→ working login/logout system - ✅ Challenge project completed
- ✅ Quiz finished
🏁 Next Step: In Module 11, you’ll master Error Handling and Debugging — learning to catch and manage PHP errors like a pro. You’ll explore try/catch, logging, and practical debugging techniques used in production WordPress environments.