Lesson 7 of 7
Mini Project: Blog System - Part 7 (Security Hardening)
Apply all security learnings to the Blog System - add CSRF protection to all forms, use security headers middleware, implement secure registration/login with bcrypt, custom error handlers for production, and a secure admin middleware that checks role.
Blog Part 7 - Full Security Layer
<?php
declare(strict_types=1);
// public/index.php - secured bootstrap
define("IS_PRODUCTION", ($_ENV["APP_ENV"] ?? "production") === "production");
// Security headers - first thing before ANY output
sendSecurityHeaders();
// Error handling
configureErrorReporting(IS_PRODUCTION);
set_exception_handler(function(Throwable $e): void {
error_log("Uncaught: " . get_class($e) . ": " . $e->getMessage() . "
" . $e->getTraceAsString());
http_response_code(500);
IS_PRODUCTION ? include "../views/errors/500.php" : throw $e;
exit;
});
// Session security
ini_set("session.cookie_httponly", "1");
ini_set("session.cookie_secure", IS_PRODUCTION ? "1" : "0");
ini_set("session.cookie_samesite", "Strict");
session_start();
// ── Auth Service - registration & login ───────────────────────
class AuthService {
public function __construct(private readonly PDO $pdo) {}
public function register(string $email, string $password, string $name): array {
$email = strtolower(trim($email));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) throw new InvalidArgumentException("Invalid email.");
if (strlen($password) < 8) throw new InvalidArgumentException("Password must be at least 8 characters.");
if (mb_strlen(trim($name)) < 2) throw new InvalidArgumentException("Name too short.");
$exists = $this->pdo->prepare("SELECT id FROM users WHERE email = :email")->execute([":email" => $email]);
if ($this->pdo->query("SELECT id FROM users WHERE email = '" . $email . "' LIMIT 1")->fetch()) {
throw new RuntimeException("An account with this email already exists.");
}
$hash = password_hash($password, PASSWORD_BCRYPT, ["cost" => 12]);
$stmt = $this->pdo->prepare("INSERT INTO users (name, email, password, created_at) VALUES (:name, :email, :pass, UTC_TIMESTAMP())");
$stmt->execute([":name" => $name, ":email" => $email, ":pass" => $hash]);
return ["id" => (int) $this->pdo->lastInsertId(), "email" => $email, "name" => $name];
}
public function login(string $email, string $password): ?array {
$email = strtolower(trim($email));
$stmt = $this->pdo->prepare("SELECT id, name, email, password, role FROM users WHERE email = :email AND deleted_at IS NULL LIMIT 1");
$stmt->execute([":email" => $email]);
$user = $stmt->fetch();
// Always verify hash - prevents timing-based user enumeration
$hash = $user["password"] ?? password_hash("dummy", PASSWORD_BCRYPT);
if (!$user || !password_verify($password, $hash)) {
return null; // same code path - no leakage
}
if (password_needs_rehash($user["password"], PASSWORD_BCRYPT, ["cost" => 12])) {
$newHash = password_hash($password, PASSWORD_BCRYPT, ["cost" => 12]);
$this->pdo->prepare("UPDATE users SET password = :h WHERE id = :id")->execute([":h" => $newHash, ":id" => $user["id"]]);
}
return $user;
}
}
// ── Login controller ─────────────────────────────────────────
function loginStore(AuthService $auth): void {
validateCsrf(); // CSRF check first
$email = trim($_POST["email"] ?? "");
$password = $_POST["password"] ?? "";
$user = $auth->login($email, $password);
if ($user === null) {
flashMessage("error", "Invalid email or password.");
header("Location: /login");
exit;
}
session_regenerate_id(true); // prevent session fixation
$_SESSION["user_id"] = $user["id"];
$_SESSION["user_name"] = $user["name"];
$_SESSION["role"] = $user["role"];
$_SESSION["logged_in"] = true;
$redirect = filter_input(INPUT_GET, "redirect", FILTER_SANITIZE_URL) ?? "/dashboard";
if (str_starts_with($redirect, "http")) $redirect = "/dashboard"; // block open redirect
header("Location: $redirect");
exit;
}Quick Quiz
Module Quiz
What makes prepared statements immune to SQL injection?
Tip
Tip
Practice Mini Project Blog System Part 7 Security Hardening in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Mini Project: Blog System - Part 7 (Security Hardening)
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project Blog System Part 7 Security Hardening from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Mini Project Blog System Part 7 Security Hardening is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?