November 19, 2026 - 11:04
PHP Lesson 03 — Read and Validate a Task Form Image
PHP Tutorials

PHP Lesson 03 — Read and Validate a Task Form

0 Comments

Add a box to the page

In lesson two we opened the PHP file whenever we wanted to add a task. Let’s type a title in a box instead. First we’ll see what arrives in PHP, then decide what to do with it.

Create public/form-demo.php in the previous lesson’s project. Save this file and visit http://127.0.0.1:8000/form-demo.php with your local server running.

PHP
<?php
$sent = $_POST['title'] ?? null;
var_dump($sent);
?>
<form method="post">
  <label>Task title <input name="title" required></label>
  <button>Submit</button>
</form>

The first page load shows NULL. It is a GET with no form submission. Submit “Buy tea” and var_dump() shows that PHP received a string. The input’s name="title" is how PHP finds it under $_POST['title']. Give them different names and you get NULL again.

What happens if we send three spaces?

Replace var_dump($sent); in the demo with this.

PHP
if (is_string($sent)) {
    var_dump($sent, trim($sent));
}

Send three spaces. You should see the original and trimmed strings.

TEXT
string(3) "   "
string(0) ""

The browser’s required check accepted the filled field. The trimmed value has no title left. That is the rule we want PHP to enforce on every submission.

Put that rule into the task page

Switch to public/index.php. Add this function after e() in the PHP section. mixed accepts the types we might receive, and ?string allows either a string or null as the result.

PHP
function validateTitle(mixed $value): ?string
{
    if (!is_string($value)) {
        return null;
    }
    $title = trim($value);
    return $title !== '' && strlen($title) <= 120 ? $title : null;
}

Check the type before calling trim(). Then check for an empty title and enforce the 120-byte limit. strlen() counts bytes, so some characters use more than one.

Add the next block above the task array. Every request starts with default values for $input, $preview and $error. The POST branch fills them when a form arrives.

PHP
$error = null;
$input = '';
$preview = null;

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $input = is_string($_POST['title'] ?? null) ? $_POST['title'] : '';
    $preview = validateTitle($input);
    if ($preview === null) {
        http_response_code(422);
        $error = 'Enter a title of 1 to 120 bytes.';
    }
}

Under the <h1>Task list</h1> heading, add the form and messages. The existing list and its foreach can stay where they are.

PHP
<?php if ($error !== null): ?>
  <p role="alert"><?= e($error) ?></p>
<?php endif; ?>
<form method="post" action="/">
  <label for="title">Task title</label>
  <input id="title" name="title" value="<?= e($input) ?>" required>
  <button><?= 'Preview task' ?></button>
</form>
<?php if ($preview !== null): ?><p>Preview: <?= e($preview) ?></p><?php endif; ?>

The input shows what you typed so you can correct it. The preview shows the title that passed the check. Both values go through e() when printed in the HTML.

At http://127.0.0.1:8000/, submit a regular title and then three spaces. Look for a preview the first time and an error the second. Open the address in a fresh tab and the preview vanishes. It belongs to that one request. We will save tasks in lesson six. You can remove form-demo.php now.

Complete working files

Start with the files that change in this lesson. If you completed the previous lesson, the other files are already in your project.

public/index.php
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;
}

$error = null;
$input = '';
$preview = null;

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $input = is_string($_POST['title'] ?? null) ? $_POST['title'] : '';
    $preview = validateTitle($input);
    if ($preview === null) {
        http_response_code(422);
        $error = 'Enter a title of 1 to 120 bytes.';
    }
}

$tasks = [
    ['title' => 'Read the lesson', 'done' => true],
    ['title' => 'Run the example', 'done' => false],
];
?>
<!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="/">
  <label for="title">Task title</label>
  <input id="title" name="title" value="<?= e($input) ?>" required>
  <button><?= 'Preview task' ?></button>
</form>
<?php if ($preview !== null): ?><p>Preview: <?= e($preview) ?></p><?php endif; ?>
<?php if ($tasks === []): ?><p>No matching tasks.</p><?php endif; ?>
<ul>
<?php foreach ($tasks as $task): ?>
  <li>
    <?= e($task['title']) ?> — <?= $task['done'] ? 'Completed' : 'Pending' ?>
  </li>
<?php endforeach; ?>
</ul>
</html>

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

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment