Final project: a blog with login
You have reached the final project. You will build, from start to finish, a blog with registration, login and article management, applying everything learned in the eight weeks: strict types, safe forms, OOP, Composer, PDO with SQLite, sessions, hashed passwords and a mini-MVC. This is a portfolio project: when finished, you will have a real application you can show. Take your time, advance step by step and test each step in the browser before continuing with the next one.
Brief and requirements
Create the application "PHP Blog". Anonymous visitors can see the list of articles and read each one. Registered users can log in and, once inside, create articles, and edit and delete only their own. All code uses PHP 8.3 with declare(strict_types=1), Composer with PSR-4 autoload (namespace App\), an MVC structure with its own router and SQLite as the database, stored outside the public folder. It must display correctly in the browser, with valid HTML and simple CSS; design is not what matters, security and structure are.
- Public routes: GET / (list paginated at 5 articles per page with ?page=), GET /posts/{id} (detail).
- Accounts: registration (/register), login (/login) and logout (POST /logout).
- Private routes: create (/posts/new), edit (/posts/{id}/edit) and delete (POST /posts/{id}/delete), only for the author.
- Security: prepared statements, password_hash, session_regenerate_id after login, CSRF token on every POST, server-side validation and htmlspecialchars on all output.
- Errors: custom exceptions, 404 for a missing article, 403 if someone tries to edit another user's article, generic 500 in production with a log.
- Structure: Router, View, controllers, repositories, enum PostStatus (draft, published) and an .env.example file.
Step 1: database and model
Start with the data, because everything else depends on it. Create a script bin/migrate.php that opens the database and runs the schema. Each article belongs to a user through a foreign key, and the status is stored as text controlled by the enum. Then create PostRepository and UserRepository with small, typed methods. Test the repositories with a console script before building any page: if the data works, the rest will be much easier.
-- Schema (SQLite)
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
title TEXT NOT NULL,
body TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'draft',
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);<?php
// File: src/Repository/PostRepository.php (write methods)
declare(strict_types=1);
namespace App\Repository;
use App\Enum\PostStatus;
use PDO;
final class PostRepository
{
public function __construct(private PDO $pdo)
{
}
/** @return list<array<string, mixed>> */
public function page(int $page, int $perPage = 5): array
{
$stmt = $this->pdo->prepare(
'SELECT id, title, created_at FROM posts WHERE status = :status
ORDER BY id DESC LIMIT :limit OFFSET :offset'
);
$stmt->bindValue(':status', PostStatus::Published->value);
$stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', max(0, ($page - 1) * $perPage), PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll();
}
public function create(int $userId, string $title, string $body, PostStatus $status): int
{
$stmt = $this->pdo->prepare(
'INSERT INTO posts (user_id, title, body, status) VALUES (:u, :t, :b, :s)'
);
$stmt->execute([':u' => $userId, ':t' => $title, ':b' => $body, ':s' => $status->value]);
return (int) $this->pdo->lastInsertId();
}
// Only the owner may update: the user_id is part of the WHERE clause
public function update(int $id, int $userId, string $title, string $body, PostStatus $status): bool
{
$stmt = $this->pdo->prepare(
'UPDATE posts SET title = :t, body = :b, status = :s WHERE id = :id AND user_id = :u'
);
$stmt->execute([':t' => $title, ':b' => $body, ':s' => $status->value, ':id' => $id, ':u' => $userId]);
return $stmt->rowCount() === 1;
}
public function delete(int $id, int $userId): bool
{
$stmt = $this->pdo->prepare('DELETE FROM posts WHERE id = :id AND user_id = :u');
$stmt->execute([':id' => $id, ':u' => $userId]);
return $stmt->rowCount() === 1;
}
}Step 2: securing the actions
Every action that changes data follows the same pattern, and it is worth writing it only once. First require a logged-in session; if not, redirect to /login. Second, check the CSRF token. Third, validate the data and return the errors to the view. Fourth, check that the article belongs to the user: although the repository already filters by user_id, the controller must answer 403 clearly. Fifth, run the action and redirect (Post/Redirect/Get) with a flash message. A failure at any step stops the flow.
Step 3: testing and completion criteria
Before calling the project finished, test it as an attacker would. Register two users and check that the second cannot edit or delete the first one's articles, neither by changing the id in the URL nor by sending the POST by hand. Type <script>alert(1)</script> in a title and verify it is displayed as text. Type ' OR 1=1 -- in the login email and check that it does not get in. Remove the CSRF token from a form and confirm the 403. Open the .sqlite file and check that the passwords are hashes starting with $2y$.
- Criterion 1: the project installs with composer install and php bin/migrate.php, and starts with php -S localhost:8000 -t public public/index.php.
- Criterion 2: all routes in the brief work and permissions are respected.
- Criterion 3: there is no concatenated SQL, no unescaped output and no secrets in the code.
- Criterion 4: all files use declare(strict_types=1) and types on parameters and returns.
- Criterion 5: .gitignore (with .env, vendor and var), .env.example and a short README with instructions exist.
- Optional extras: title search with GET, comments on articles, or PHPUnit tests for the repository.
检验所学
第 1 / 7What does the clause AND user_id = :u do in the project UPDATE and DELETE?
✎ 我的笔记
仅保存在此浏览器中。登录后可保存到账号。0/5000 字符