Objective: Learn how to store user information across multiple pages using sessions and cookies,
and build a secure login/logout system to manage authentication.
A session stores temporary data about a user while they’re browsing your website.
✅ Example uses:
PHP identifies each user with a unique session ID stored on the server.
<?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.
<?php
session_start();
echo "Welcome back, " . $_SESSION["username"];
?>✅ The user’s name carries over — even on a different page.
<?php
session_start();
session_unset(); // Removes session variables
session_destroy(); // Destroys session
echo "Session ended.";
?>🧠 This is typically used for logging users out.
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.
<?php
setcookie("username", "Yogi", time() + (86400 * 7)); // 7 days
echo "Cookie set!";
?>✅ time() + (86400 * 7) means it expires in 7 days.
<?php
if (isset($_COOKIE["username"])) {
echo "Welcome back, " . $_COOKIE["username"];
} else {
echo "Hello, new visitor!";
}
?><?php
setcookie("username", "", time() - 3600); // Past time = deleted
echo "Cookie removed.";
?>| 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.
Let’s build a small authentication workflow.
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.
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.
logout.php<?php
session_start();
session_destroy();
header("Location: login.php");
exit;
?>✅ Logs out the user and clears the session.
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 MeNow, 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"] ?? ''; ?>">password_hash().session_regenerate_id(true);htmlspecialchars() or filter_input()).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.
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"];
}
?>
Create login.php, dashboard.php, logout.php using examples above.
✅ Test logging in/out and see how the session persists.
Goal: Build a complete login/logout flow using sessions, cookies, and input validation.
Steps:
login-system.php.<?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.
| # | 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 |
Objective: Expand your login project into a real-world protected dashboard app.
Requirements:
✅ When a user revisits the site:
session-demo.php → works across pagescookie-demo.php → sets and retrieves cookielogin.php + dashboard.php + logout.php → working login/logout system
🏁 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.