Skip to content
Tutorials Center
My learning

Topics

Lesson 128 of 147 ยท Projects

Project: To-Do List

Build a PHP to-do list in four stages - an array of tasks, form commands from $_POST, escaped HTML, a PDO SQLite repository and a front controller.

A to-do list is the "hello world" of web applications, and for good reason: it's small enough to finish in an afternoon, yet it touches almost everything a real PHP app does. You keep data, accept commands from a form, validate them, store the result somewhere that survives the next request, and turn it all back into HTML without letting a sneaky task title break the page.

In this project you'll build the app in four stages. Each stage is a complete program you can run, change and break. You'll start with tasks in a plain array, then handle add, complete and delete commands that arrive in $_POST, then move the data into an SQLite database with PDO, and finally wrap everything in a small front controller that answers requests with status codes, redirects and a rendered page.

Our editor runs PHP on the command line, not behind a web server, so there are no real browsers or form submissions here. Stages 2 to 4 simulate requests by filling $_POST and $_GET (or plain arrays) at the top of the script and then calling the same code a server would call. The last section shows how to run the finished app for real.

The plan

Before writing code, decide what a task is and what the app must do with it:

  • A task has an id (a positive integer), a title (1 to 100 characters, trimmed) and a done flag.
  • The app supports four commands: add a task, toggle it between done and not done, delete it, and clear all completed tasks.
  • Every command is validated before it changes anything. A blank title or an unknown id produces an error message, never a broken list.
  • Every piece of user text is escaped when it's printed as HTML, using htmlspecialchars.

You'll also keep the logic separate from input and output. The functions that change the list don't read $_POST or echo anything; they take values and return values. That makes them easy to test, and it's the reason stage 3 can swap the array for a database without rewriting the rest.

Stage 1: tasks in an array

The first version keeps the whole list in one associative array with two keys: nextId, the id the next task will get, and tasks, the tasks themselves keyed by id. Keying by id makes "find task 3" a simple isset($list['tasks'][3]) instead of a search through the array.

Each function receives the list and returns a new list. PHP copies arrays when you pass them to a function (more precisely, it copies them lazily, the moment you change them), so the caller's list is never modified behind its back. You'll see $list = addTask($list, ...), which makes every change visible at the call site.

Errors are reported with exceptions. addTask throws an InvalidArgumentException for a bad title, and the other functions throw one for an unknown id. The command loop at the bottom catches them and prints a message, so one bad command doesn't stop the program. (See Exceptions for the details of try and catch.)

PHP Stage 1: a to-do list in an array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output starts with one line per command: six OKs and two errors, The title cannot be empty. for the blank title and There is no task #7. for the toggle of a task that doesn't exist. Then comes the list:

TEXT
[ ] #1 Buy oat milk
[x] #2 Call the dentist
[ ] #4 Read chapter 4
2 of 3 left

A few details are worth noticing:

  • Ids are never reused. Task 3 was deleted, and the next task got id 4. If ids were reused, a stale link like "delete task 3" in an old browser tab could delete the wrong task.
  • trim before validating. ' Call the dentist ' is stored without the spaces, and ' ' counts as empty. Users paste text with stray whitespace all the time.
  • mb_strlen, not strlen. A title in Greek or with an emoji has more bytes than characters. Unicode and Multibyte Strings explains the difference.
  • foreach ($commands as [$command, $argument]) unpacks each command pair with destructuring, and match picks the function. An unknown command would throw UnhandledMatchError, which this loop deliberately doesn't catch: that would be a bug in our own code, not bad user input.
  • array_filter keeps keys, so after clearing completed tasks, task 4 still has the key 4. That's exactly what we want here, since the keys are the ids.

Stage 2: commands from a form

On the web, commands arrive as HTTP requests. The page shows a form for adding a task and, next to every task, small forms with "Done" and "Delete" buttons. When the user clicks one, the browser sends a POST request, and PHP puts the form fields into the $_POST superglobal. A click on "Done" for task 2 produces something like this:

TEXT
POST / HTTP/1.1
Content-Type: application/x-www-form-urlencoded

action=toggle&id=2

and PHP turns the body into $_POST = ['action' => 'toggle', 'id' => '2']. Notice that id is the string '2'. Everything in $_POST is a string (or an array, if the field name ends in []), and a field can be missing altogether if someone sends the request by hand. So the handler must check each field before trusting it.

handlePost does exactly that. It reads action with ?? '' so a missing field becomes an empty string, converts the id with filter_var(..., FILTER_VALIDATE_INT), which returns false for anything that isn't a clean whole number ('2abc', '1.5', ''), and then calls the stage 1 functions. It returns the new list and an optional error message. The Handling Forms lesson covers filter_var in more depth.

The second new piece is renderHtml. Every task title passes through a tiny helper e() that calls htmlspecialchars. One of the simulated requests below adds a task whose title is an HTML <script> tag, the classic test for cross-site scripting. Without escaping, every visitor's browser would run it.

PHP Stage 2: handling simulated form posts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Requests 1 to 4 succeed. Request 5 is rejected because '2abc' isn't a valid id, request 6 because task 99 doesn't exist, request 7 because the title field is missing and request 8 because explode isn't an action. The rendered list then contains this line for the second task:

HTML
<li>&lt;script&gt;alert(&quot;hi&quot;)&lt;/script&gt; <button name="action" ...

The browser would display the text <script>alert("hi")</script> instead of running it, and the & in "Fix the bike & oil the chain" becomes &amp;, which is how HTML spells a literal ampersand. (Our editor shows the HTML source as plain text; a web server would send it to a browser to render.)

match (true) is a handy way to write "the first condition that holds wins". Each arm is a full boolean expression, and default throws an exception, since PHP 8.0 lets you use throw as an expression. See switch and match.

The loop foreach ($requests as $number => $_POST) assigns each simulated form to the real $_POST variable, which is allowed in the CLI. It's only a trick for this demo; in a real app PHP fills $_POST once per request and you never assign to it.

The problem stage 2 doesn't solve

Run stage 2 in your head as a real web app: request 1 adds a task, the response is sent, and the PHP process forgets everything. Each HTTP request starts with fresh variables (the How PHP Works lesson explains this "shared-nothing" model). Our $list only survived between requests because the demo ran them all inside one script. A real to-do list needs storage that outlives a request: a file, a session, or a database. For data that many requests read and write, a database is the right choice.

Stage 3: storing tasks in SQLite

SQLite is a complete SQL database stored in a single file, and PHP talks to it through PDO, the same API you'd use for MySQL or PostgreSQL. In our editor, new PDO('sqlite::memory:') creates a database in memory that disappears when the script ends; on a server you'd pass a file path instead.

All SQL lives in one class, TaskRepository. The rest of the app calls methods like add() and toggle() and never sees a query. That pattern, a repository, is covered in CRUD with PDO, and it pays off right away: if you later move to MySQL, only this class changes.

Three PDO habits run through the code:

  • The connection uses PDO::ERRMODE_EXCEPTION (the default since PHP 8.0, but stating it makes the intent clear) and PDO::FETCH_ASSOC, so rows come back as arrays with column names as keys.
  • Every value from the user goes through a prepared statement with placeholders like :title. The SQL and the data travel separately, so no title can change the meaning of the query. Prepared Statements shows what goes wrong otherwise.
  • Methods that change one row check rowCount(). If it's 0, the id didn't exist, and the method returns false so the caller can show a message.
PHP Stage 3: a repository with PDO and SQLite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first toggle returns true, the toggle of task 42 returns false because no row matched. The third task's title is a famous SQL injection attempt. With a prepared statement it's stored as harmless text (and then deleted by delete(3), which returns true). Had we glued the title into the SQL string with ., the apostrophe would have ended the string literal early and the rest would have run as SQL.

The SQL also does some of the work for us:

  • INTEGER PRIMARY KEY AUTOINCREMENT gives each task an id that's never reused, the same rule we enforced by hand with nextId in stage 1.
  • done = 1 - done flips 0 to 1 and 1 to 0 in a single statement. Reading the row, flipping it in PHP and writing it back would take two queries and could lose an update if two requests arrived at the same moment.
  • ORDER BY done, id lists open tasks first, then completed ones, each group in the order they were added.
  • exec() returns the number of affected rows, which clearCompleted() passes on.

Since PHP 8.1, the SQLite driver returns integer columns as PHP ints, so $task['id'] is 1, not '1'. The MySQL driver (mysqlnd) does the same since 8.1; older versions returned strings, which is one reason the repository casts lastInsertId() (always a string) and fetchColumn() explicitly.

Stage 4: a front controller

The final stage turns the pieces into an application. A front controller is one function (on a server, one index.php file) that receives every request and decides what to do with it. You'll meet the pattern again in Front Controllers and Routing.

Our controller, handleRequest, takes the HTTP method, the query string values ($_GET), the form fields ($_POST) and the repository, and returns a response array with a status code, headers and a body. It doesn't call header() or echo itself; a few lines at the end of the real index.php do that. Returning the response as data is what lets us test the controller with simulated requests here.

The controller follows the POST-redirect-GET pattern:

  1. A GET request shows the page.
  2. A POST request changes data and then answers with a 303 See Other redirect back to the page, instead of HTML.
  3. The browser follows the redirect with a fresh GET.

Without step 2, refreshing the page after adding a task would make the browser offer to resubmit the form and add the task twice. With it, the last request in the browser's history is always a harmless GET. The HTTP Headers and Redirects lesson covers status codes and the Location header.

The redirect carries a message for the next page in the query string, like /?msg=added. The message is a short code, never free text, and the page looks the code up in a fixed array. That way nobody can craft a link that makes your page display arbitrary text. (A real app would more often store the message in the session as a "flash message", shown in the Sessions lesson.) The page also supports a filter, ?filter=open or ?filter=done, checked against a whitelist.

PHP Stage 4: the complete app with simulated requests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the output from top to bottom and you can follow every request:

  • The two valid adds answer 303 with Location: /?msg=added. The empty title redirects to /?msg=invalid-title, so the next page shows the error.
  • Toggling task 1 gives msg=updated; deleting task 8, which never existed, gives msg=missing.
  • action=rename isn't something the app understands, so it gets a plain 400 Bad request. A DELETE request gets 405 Method Not Allowed with an Allow header listing the methods we do accept.
  • The first GET shows "Task updated." and only the open task, because of filter=open. Its title is escaped: Plan &lt;b&gt;Friday&lt;/b&gt; lunch.
  • The last GET tries to inject a message and an invalid filter. The message code isn't in MESSAGES, so no message appears, and the unknown filter falls back to all, which shows both tasks.

One thing to notice in the repository: all() puts $where straight into the SQL string. That's safe only because $where comes from a match with fixed strings, never from the user. Placeholders can stand in for values, but not for SQL keywords, column names or whole clauses, so whitelisting is the right tool there. Pagination, Search and Database Patterns uses the same technique for sortable columns.

This app has no login and no CSRF protection, so any website could make a visitor's browser post to it. That's acceptable for a private learning project on your own machine, but not on the public internet. The next project, Project: Contact Form with Validation, adds a CSRF token, and Preventing CSRF explains the attack.

Running it on a real server

To run the finished app in a browser, split stage 4 into a few files. One way to lay it out:

TEXT
todo/
โ”œโ”€โ”€ data/                  โ† the SQLite file lives here, outside the web root
โ”œโ”€โ”€ public/
โ”‚   โ””โ”€โ”€ index.php          โ† the only file the web server can serve
โ””โ”€โ”€ src/
    โ”œโ”€โ”€ TaskRepository.php
    โ””โ”€โ”€ app.php            โ† handleRequest(), renderPage(), e(), ...

public/index.php connects to a database file, builds the request from the real superglobals, and sends the response:

PHP
<?php

declare(strict_types=1);

require __DIR__ . '/../src/TaskRepository.php';
require __DIR__ . '/../src/app.php';

$pdo = new PDO('sqlite:' . __DIR__ . '/../data/todo.sqlite', options: [
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

$response = handleRequest($_SERVER['REQUEST_METHOD'], $_GET, $_POST, new TaskRepository($pdo));

http_response_code($response['status']);
foreach ($response['headers'] as $name => $value) {
    header("$name: $value");
}
echo $response['body'];

Then start PHP's built-in development server from the todo folder and open http://localhost:8000:

Terminal
php -S localhost:8000 -t public

The page also needs the add form itself, which stage 4 left out to keep the output short:

HTML
<form method="post">
  <input name="title" maxlength="100" required>
  <button name="action" value="add">Add</button>
</form>

maxlength and required give the user instant feedback in the browser, but they're only a convenience: anyone can send a request without them, so the server-side checks in handlePost stay. Form Validation explains why both layers matter. The data/ folder must be writable by the PHP process, because SQLite creates a temporary journal file next to the database while writing.

Ideas for extending the app

  • Edit titles. Add an edit action with an id and a title, reusing the same validation as add.
  • Due dates. Add a due_on TEXT column, validate the input with DateTimeImmutable::createFromFormat('Y-m-d', ...) (see Dates and Times), and highlight overdue tasks.
  • Several lists. Add a lists table and a list_id foreign key, and route /lists/3 to one list, as the blog project does for posts.
  • A CSRF token on every form, as described in the warning above.
  • Tests. Because handleRequest returns data, you can write assertions like "posting an empty title redirects to msg=invalid-title" with the mini test runner from Testing PHP Code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A user submits the form with id=2abc. What does filter_var('2abc', FILTER_VALIDATE_INT) return?

    FILTER_VALIDATE_INT only accepts a string that is a complete, valid integer. Anything else, including trailing letters, gives false, which the handler treats as an invalid request.
  2. 2. Why does stage 4 answer a successful POST with a 303 redirect instead of the HTML page?

    This is the POST-redirect-GET pattern. After the redirect, the last request in the browser history is a GET, so a refresh can't add the same task twice.
  3. 3. Why is it safe for TaskRepository::all() to put $where directly into the SQL string?

    The user only chooses which arm of the match runs; the SQL text itself is always one of our constant strings. Placeholders can't replace SQL clauses, so a whitelist is the correct tool.
  4. 4. In stage 2, the tasks survive between simulated requests. Why wouldn't that work on a real web server?

    PHP uses a shared-nothing model; nothing in memory survives from one request to the next. That's why stage 3 moves the tasks into a database.
  5. 5. What is printed for a task titled Tom & Jerry by e()?

    htmlspecialchars converts & to &, the HTML way of writing a literal ampersand. The browser displays it as Tom & Jerry.

Summary

  • Decide the data shape and the rules first: a task has an id, a trimmed title of 1 to 100 characters and a done flag, and ids are never reused.
  • Keep the logic in functions that take values and return values; read input and produce output at the edges.
  • Treat everything in $_POST as an untrusted string that may be missing: use ?? '', is_string and filter_var.
  • Escape every piece of user text with htmlspecialchars when you print HTML.
  • PHP forgets everything between requests, so persistent data belongs in a database. Put the SQL in a repository class and use prepared statements for every value.
  • A front controller turns a request into a status code, headers and a body; answer successful POSTs with a 303 redirect (POST-redirect-GET).
  • Whitelist anything that can't be a placeholder, such as filters, sort columns and message codes.

Next: Project: Contact Form with Validation