Could a small edit break our rule?
Lesson nine’s task list runs. Suppose we accidentally remove trim() when revisiting the title rule. The page can still open. Let’s check that rule from the terminal and then compare the browser workflow with the table.
Exercise the title rule without a form
Create tools beside public. In tools/check-titles.php, load app/functions.php after opening PHP. Add three inputs and the results we expect from them.
<?php
declare(strict_types=1);
require __DIR__ . '/../app/functions.php';
$cases = [
'trim' => [' Çay al ', 'Çay al'],
'spaces' => [' ', null],
'too long' => [str_repeat('a', 121), null],
];
The first title loses its surrounding spaces. Spaces alone and a 121-byte title should both return null. Append this loop. We used foreach to draw tasks before; here it runs one check per example.
$failed = false;
foreach ($cases as $name => [$input, $expected]) {
$actual = validateTitle($input);
if ($actual !== $expected) {
echo "FAIL: $name", PHP_EOL;
$failed = true;
continue;
}
echo "OK: $name", PHP_EOL;
}
exit($failed ? 1 : 0);
From the project root run php tools/check-titles.php. Expect three OK lines. A failure identifies the case and returns status 1 to the shell. To see that path, temporarily change the first expected title and run it again. Restore the expected title after the check.
Look at the rows as well as the page
Run the same query in your local practice database before and after each browser step.
SELECT id, title, done FROM tasks ORDER BY id;
| Try this | On the page | In the query |
|---|---|---|
| Add a new title | The title appears after returning to the list | One new ID |
| Refresh twice | The same task is visible | No additional ID |
| Submit spaces | A form error appears | Same row count |
| Complete the new task | It appears under Completed | Its done value is 1 |
| Edit its title | The new title appears with the status | Same ID and same done |
If refreshing creates a row, revisit the 303 flow in lesson six. If editing changes the status, inspect the UPDATE in lesson nine. The terminal check, browser behavior and database each answer a different question. Start with the one that failed.
Complete working files
Below is the complete working version for this lesson. Save each file at the path in its heading. If you are continuing from the previous lesson, replace the matching files.
public/index.php
<?php
declare(strict_types=1);
require __DIR__ . '/../app/functions.php';
$pdo = require __DIR__ . '/../app/db.php';
session_start();
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
$csrf = $_SESSION['csrf'];
$editing = null;
$error = null;
$input = '';
if (isset($_GET['edit'])) {
$id = positiveId($_GET['edit']);
$editing = $id === null ? null : findTask($pdo, $id);
if ($editing === null) {
http_response_code(404);
exit('Task not found.');
}
$input = $editing['title'];
}
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
$submittedToken = $_POST['csrf'] ?? null;
if (!is_string($submittedToken) || !hash_equals($csrf, $submittedToken)) {
http_response_code(403);
exit('Invalid form token.');
}
$action = $_POST['action'] ?? '';
if ($action === 'state') {
$id = positiveId($_POST['id'] ?? null);
$done = $_POST['done'] ?? null;
if ($id === null || !in_array($done, ['0', '1'], true)) {
http_response_code(400);
exit('Invalid task state.');
}
$statement = $pdo->prepare('UPDATE tasks SET done = ? WHERE id = ?');
$statement->execute([(int) $done, $id]);
redirectToList();
}
if (!in_array($action, ['add', 'edit'], true)) {
http_response_code(400);
exit('Invalid action.');
}
if ($action === 'edit') {
$id = positiveId($_POST['id'] ?? null);
$editing = $id === null ? null : findTask($pdo, $id);
if ($editing === null) {
http_response_code(404);
exit('Task not found.');
}
}
$input = is_string($_POST['title'] ?? null) ? $_POST['title'] : '';
$title = validateTitle($input);
if ($title === null) {
http_response_code(422);
$error = 'Enter a title of 1 to 120 bytes.';
} else {
if ($action === 'edit') {
$statement = $pdo->prepare('UPDATE tasks SET title = ? WHERE id = ?');
$statement->execute([$title, $id]);
} else {
$statement = $pdo->prepare('INSERT INTO tasks (title) VALUES (?)');
$statement->execute([$title]);
}
redirectToList();
}
}
$filter = $_GET['filter'] ?? 'all';
if (!in_array($filter, ['all', 'pending', 'done'], true)) {
$filter = 'all';
}
if ($filter === 'all') {
$tasks = $pdo->query('SELECT id, title, done FROM tasks ORDER BY id')->fetchAll();
} else {
$statement = $pdo->prepare('SELECT id, title, done FROM tasks WHERE done = ? ORDER BY id');
$statement->execute([$filter === 'done' ? 1 : 0]);
$tasks = $statement->fetchAll();
}
require __DIR__ . '/../app/view.php';
app/view.php
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Task list</title>
<h1>Task list</h1>
<?php if ($error !== null): ?>
<p role="alert"><?= e($error) ?></p>
<?php endif; ?>
<form method="post" action="/">
<input type="hidden" name="csrf" value="<?= e($csrf) ?>">
<input type="hidden" name="action" value="<?= $editing ? 'edit' : 'add' ?>">
<?php if ($editing): ?>
<input type="hidden" name="id" value="<?= (int) $editing['id'] ?>">
<?php endif; ?>
<label for="title">Task title</label>
<input id="title" name="title" value="<?= e($input) ?>" required>
<button><?= $editing ? 'Save changes' : 'Add task' ?></button>
</form>
<?php if ($editing): ?><p><a href="/">Cancel editing</a></p><?php endif; ?>
<nav aria-label="Task filters">
<a href="/?filter=all">All</a>
<a href="/?filter=pending">Pending</a>
<a href="/?filter=done">Completed</a>
</nav>
<p>Filter: <?= e($filter) ?></p>
<?php if ($tasks === []): ?><p>No matching tasks.</p><?php endif; ?>
<ul>
<?php foreach ($tasks as $task): ?>
<li>
<?= e($task['title']) ?> — <?= $task['done'] ? 'Completed' : 'Pending' ?>
<form method="post" action="/">
<input type="hidden" name="csrf" value="<?= e($csrf) ?>">
<input type="hidden" name="action" value="state">
<input type="hidden" name="id" value="<?= (int) $task['id'] ?>">
<input type="hidden" name="done" value="<?= $task['done'] ? 0 : 1 ?>">
<button><?= $task['done'] ? 'Mark pending' : 'Complete' ?></button>
</form>
<a href="/?edit=<?= (int) $task['id'] ?>">Edit</a>
</li>
<?php endforeach; ?>
</ul>
</html>
app/functions.php
<?php
declare(strict_types=1);
function e(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function validateTitle(mixed $value): ?string
{
if (!is_string($value)) {
return null;
}
$title = trim($value);
return $title !== '' && strlen($title) <= 120 ? $title : null;
}
function redirectToList(): never
{
header('Location: /', true, 303);
exit;
}
function positiveId(mixed $value): ?int
{
if (!is_string($value)) {
return null;
}
$id = filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
return $id === false ? null : $id;
}
function findTask(PDO $pdo, int $id): ?array
{
$statement = $pdo->prepare('SELECT id, title, done FROM tasks WHERE id = ?');
$statement->execute([$id]);
$task = $statement->fetch();
return $task === false ? null : $task;
}
app/db.php
<?php
declare(strict_types=1);
$host = getenv('DB_HOST') ?: '127.0.0.1';
$port = getenv('DB_PORT') ?: '3306';
$database = getenv('DB_NAME') ?: 'php_tasks';
$user = getenv('DB_USER') ?: 'php_tasks';
$password = getenv('DB_PASS');
$dsn = "mysql:host=$host;port=$port;dbname=$database;charset=utf8mb4";
return new PDO($dsn, $user, $password === false ? '' : $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
schema.sql
CREATE TABLE tasks (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(120) NOT NULL,
done TINYINT UNSIGNED NOT NULL DEFAULT 0,
CHECK (done IN (0, 1))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
seed.sql
INSERT INTO tasks (title, done)
VALUES ('Read the lesson', 1), ('Run the example', 0);
tools/check-titles.php
<?php
declare(strict_types=1);
require __DIR__ . '/../app/functions.php';
$cases = [
'trim' => [' Çay al ', 'Çay al'],
'spaces' => [' ', null],
'too long' => [str_repeat('a', 121), null],
];
$failed = false;
foreach ($cases as $name => [$input, $expected]) {
$actual = validateTitle($input);
if ($actual !== $expected) {
echo "FAIL: $name", PHP_EOL;
$failed = true;
continue;
}
echo "OK: $name", PHP_EOL;
}
exit($failed ? 1 : 0);
After saving the files, run php -S 127.0.0.1:8000 -t public in the project folder and open http://127.0.0.1:8000/. If the server is already running from that project folder, refresh the page.
Related Articles