Thuta Learning
PHP
IntermediateProgrammingBeginner

Form Validation

PHPLesson 1930 min

What you'll walk away with

  • Separate validation, sanitization and output escaping, and say which job each one does
  • Validate email, integer, boolean and URL data with filter_var and read its return values correctly
  • Check required fields, lengths (with mb_strlen) and patterns (with preg_match) and gather every error in an array
  • Explain why server-side validation is mandatory even when the browser already checks the form

Explain it simply

Validation in plain language

Validation is a bouncer at the door of your code. Whatever arrives from a form, a URL or an API call is a stranger's claim: the sender says it is an email address, an age or a quantity, and your job is to check the claim before letting it in. Data that passes goes on to the database or the business logic; data that fails is turned away with a clear message saying what to fix.

The check has to happen in PHP, on the server. Browsers can help with required and type=email, but those only make the form friendlier. They do not protect you, because anyone can send a request without using your form at all.

Problem → Why → Solution

The problem: saving whatever arrives

Picture a signup page that stores whatever arrives. One visitor leaves the email blank, another types 'soon', a third registers with the age -5, and a script posts a username that is two megabytes long. Every row goes into the database, and later the newsletter job crashes on the bad email, the age report shows negative numbers, and nobody can tell which signups are real.

A second trap is validating badly: checking one field, finding it wrong and returning at once. The visitor fixes the email, submits again, and only then learns that the age was wrong too. Three round trips for three mistakes feels like the form is arguing with them.

signup-unsafe.php
<?php
// Dangerous: trusts every value exactly as it arrived.
$email = $_POST['email'];
$age = $_POST['age'];

if ($email === '') {
    die('Email is required.');   // stops at the first problem
}

$stmt = $pdo->prepare('INSERT INTO members (email, age) VALUES (?, ?)');
$stmt->execute([$email, $age]);  // 'soon' and -5 are saved happily

Why check every field, every time

A database column accepts any value of the right type, so it cannot tell you that 'soon' is not a real email. Only your PHP code knows the business rules, which means that code must check each field and keep going until it has seen every problem. Collecting the errors in an array lets you show one complete list, and an empty array becomes the single yes-or-no answer your application acts on.

Core concept: normalise, check, collect

Three different jobs get mixed up under the word 'cleaning', so name them separately. Validation asks 'is this value acceptable?' and answers yes or no. Sanitization changes a value into a safer or tidier one, such as trimming spaces or lower-casing an email. Escaping happens at output time, when you print a value into HTML, SQL or a URL, and it is chosen by where the value is going, not by where it came from. Validation never replaces the other two: a perfectly valid name can still contain an apostrophe that breaks a query or markup that breaks a page.

The usual order is normalise, then validate. Trim the string first, so that three spaces do not count as a name. Then test the rules for that field: required (the trimmed value is not an empty string), length (use mb_strlen so a Myanmar or accented name is measured in characters, not bytes), format (filter_var for emails, integers, URLs and booleans, or preg_match for custom patterns) and range (a minimum and a maximum). Compare with === '' for required instead of empty(), because empty('0') is true and would reject a legitimate value.

FilterAcceptsOn failure
FILTER_VALIDATE_EMAILemail address syntax (does not prove the mailbox exists)false
FILTER_VALIDATE_INTwhole numbers, optional min_range and max_range, returns the intfalse
FILTER_VALIDATE_BOOLEANyes, no, on, off, 1, 0, true, falsenull (with FILTER_NULL_ON_FAILURE)
FILTER_VALIDATE_URLURL syntax; check the scheme yourselffalse

Two return-value traps catch beginners. filter_var returns the filtered value on success, not true, so '0' validates to the integer 0, which is falsy: if (!filter_var($qty, FILTER_VALIDATE_INT)) would reject a perfectly good zero. Always compare with === false. The second point is to use what a valid result gives you: keep the integer that filter_var returns rather than the raw string.

Collect errors in an associative array keyed by field name: $errors['email'] = '...'. Do not stop at the first failure; run every check, then look at whether the array is empty at the end. The array also tells the template which inputs to highlight, and if you print the visitor's typed values back into the form, remember to escape them with htmlspecialchars.

Validation as a checklist with a verdict
  1. Receive the raw value as a string
  2. Trim, then test each rule on its own
  3. Record a message under the field name
  4. Empty errors array means accept

Never return on the first failure; the visitor should see every problem at once.

General pattern

php
$errors = [];
$field = trim((string)($input['field'] ?? ''));

if ($field === '') {
    $errors['field'] = 'Field is required.';
} elseif (mb_strlen($field) > MAX_LENGTH) {
    $errors['field'] = 'Field is too long.';
} elseif (filter_var($field, FILTER_VALIDATE_xxx) === false) {
    $errors['field'] = 'Field has the wrong format.';
}
// $errors === [] means every rule passed

Normalise the value, then test one rule per branch so each field produces at most one message, and read the final array: empty means valid. Swap the format test for preg_match or a range check as the field needs.

Worked example: a signup form that reports every problem

The function below validates one signup submission and returns an array of messages keyed by field. Two submissions are checked: a good one, and one that breaks every rule at once, so you can see all four problems come back together instead of only the first. The command line has no form, so plain arrays stand in for $_POST.

validate-signup.php
<?php
function validateSignup(array $input): array
{
    $errors = [];

    $name = trim((string)($input['name'] ?? ''));
    $email = trim((string)($input['email'] ?? ''));
    $age = trim((string)($input['age'] ?? ''));
    $username = trim((string)($input['username'] ?? ''));

    if ($name === '') {
        $errors['name'] = 'Name is required.';
    } elseif (mb_strlen($name) > 30) {
        $errors['name'] = 'Name must be at most 30 characters.';
    }

    if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        $errors['email'] = 'Enter a valid email address.';
    }

    $options = ['options' => ['min_range' => 13, 'max_range' => 120]];
    if (filter_var($age, FILTER_VALIDATE_INT, $options) === false) {
        $errors['age'] = 'Age must be a whole number from 13 to 120.';
    }

    if (preg_match('/^[a-z0-9_]{3,16}$/D', $username) !== 1) {
        $errors['username'] = 'Username: 3-16 lowercase letters, digits or underscores.';
    }

    return $errors;
}

$submissions = [
    'good form' => [
        'name' => 'မေ မေ',
        'email' => 'may@example.com',
        'age' => '29',
        'username' => 'may_29',
    ],
    'bad form' => [
        'name' => '   ',
        'email' => 'may@example',
        'age' => '7',
        'username' => 'May!',
    ],
];

foreach ($submissions as $label => $input) {
    $errors = validateSignup($input);
    echo $label, ': ', $errors === [] ? 'accepted' : count($errors) . ' problems', "\n";
    foreach ($errors as $field => $message) {
        echo "  - $field: $message\n";
    }
}

Code breakdown

  1. Normalise first$name = trim((string)($input['name'] ?? ''));

    ?? '' avoids a warning when the field was not sent at all, and the (string) cast guarantees trim() always receives a string. Spaces are removed before any rule runs.

  2. Required, then length} elseif (mb_strlen($name) > 30) {

    The elseif keeps each field to a single message: if the name is blank there is no point measuring it. mb_strlen measures a Myanmar name in characters rather than bytes.

  3. Format with filter_varif (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {

    filter_var returns the email string when it is valid and false otherwise, which is why the comparison is a strict === false. A blank email also fails this single check.

  4. Integer in a range$options = ['options' => ['min_range' => 13, 'max_range' => 120]];

    Filter options go in a nested array under the 'options' key. With it, a number like '7' fails the range and text like '29abc' fails the type, so one call checks both.

  5. Custom patternif (preg_match('/^[a-z0-9_]{3,16}$/D', $username) !== 1) {

    preg_match returns 1, 0, or false on a pattern error, so testing !== 1 is the safe form. The D modifier stops $ from also matching just before a trailing newline.

  6. Return every messagereturn $errors;

    The function prints nothing; it just returns the array, so an HTML page, a JSON API or a test can all reuse it. The caller decides what to do based on whether the array is empty.

You should see
good form: accepted
bad form: 4 problems
  - name: Name is required.
  - email: Enter a valid email address.
  - age: Age must be a whole number from 13 to 120.
  - username: Username: 3-16 lowercase letters, digits or underscores.

Reading filter_var results correctly

The best way to learn filter_var is to try it rather than guess. The script below feeds a handful of inputs to filter_var and prints each result with var_export, so false, null and integers are clearly different. Notice that FILTER_VALIDATE_INT accepts ' 42 ' by trimming it but rejects '042', and that FILTER_VALIDATE_BOOLEAN without FILTER_NULL_ON_FAILURE reports 'maybe' as plain false, so the flag is what lets you tell 'the visitor typed false' from 'this is not a boolean'.

filter-results.php
<?php
function show(string $label, mixed $result): void
{
    echo str_pad($label, 28), var_export($result, true), "\n";
}

show('INT "0"', filter_var('0', FILTER_VALIDATE_INT));
show('INT " 42 " (spaces)', filter_var(' 42 ', FILTER_VALIDATE_INT));
show('INT "042" (leading zero)', filter_var('042', FILTER_VALIDATE_INT));
show('INT "12.5"', filter_var('12.5', FILTER_VALIDATE_INT));
$bool = FILTER_VALIDATE_BOOLEAN;
show('BOOL "off"', filter_var('off', $bool, FILTER_NULL_ON_FAILURE));
show('BOOL "maybe"', filter_var('maybe', $bool, FILTER_NULL_ON_FAILURE));
show('EMAIL "ada@example"', filter_var('ada@example', FILTER_VALIDATE_EMAIL));
show('URL "example.com"', filter_var('example.com', FILTER_VALIDATE_URL));

$tricky = 'javascript://example.com/%0Aalert(1)';
$scheme = parse_url($tricky, PHP_URL_SCHEME);
show('URL "javascript://..." ok?', filter_var($tricky, FILTER_VALIDATE_URL) !== false);
show('scheme is http/https?', in_array($scheme, ['http', 'https'], true));
text
INT "0"                     0
INT " 42 " (spaces)         42
INT "042" (leading zero)    false
INT "12.5"                  false
BOOL "off"                  false
BOOL "maybe"                NULL
EMAIL "ada@example"         false
URL "example.com"           false
URL "javascript://..." ok?  true
scheme is http/https?       false

The last two lines carry an important lesson: FILTER_VALIDATE_URL happily accepts a string starting with javascript://, because it only checks syntax. When a visitor-supplied link will end up in an href, extract the scheme with parse_url and check it against an allow-list (http, https) with in_array(..., true).

Measuring length in characters, not bytes

PHP's strlen() counts the bytes in a string. An English letter is one byte in UTF-8, so the difference stays hidden, but a Myanmar letter usually takes three bytes. A rule such as 'a name is at most 30 characters' checked with strlen can therefore reject a perfectly short Myanmar name. mb_strlen counts code points (Unicode characters), and grapheme_strlen from the intl extension counts what a reader sees as one character.

length-units.php
<?php
$word = 'မြန်မာ';

echo 'strlen:          ', strlen($word), "\n";
echo 'mb_strlen:       ', mb_strlen($word), "\n";
echo 'grapheme_strlen: ', grapheme_strlen($word), "\n";
text
strlen:          18
mb_strlen:       6
grapheme_strlen: 4

Which one to pick depends on the rule. To match a database limit such as VARCHAR(n), mb_strlen is a good fit, because utf8mb4 columns count code points. Whichever you choose, use it consistently across the whole form, and keep strlen out of text-length rules.

Showing errors and keeping what the visitor typed

When validation fails you show the form again, and the visitor must not lose what they typed. Putting the typed value back into the input's value attribute is called a sticky form. That value is the visitor's own data, so it has to be escaped before it goes into HTML; otherwise markup that slipped past validation can break the page. The small e() helper in the template below keeps that job in one place.

sticky-field.php
<?php
$old = ['email' => 'may"@example.com'];       // what the visitor typed
$errors = ['email' => 'Enter a valid email address.'];

function e(string $text): string
{
    return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
?>
<label>Email
  <input name="email" value="<?= e($old['email'] ?? '') ?>">
</label>
<?php if (isset($errors['email'])): ?>
  <p class="error"><?= e($errors['email']) ?></p>
<?php endif; ?>

In real projects

Where validation shows up in real projects

Every entry point that accepts outside data validates it: registration and login forms, checkout (quantity, postcode, coupon code), and search filters in the query string, where page must be a positive integer and sort must be one of a few allowed words. API endpoints that read JSON bodies and cron scripts that read arguments or CSV rows do the same.

Frameworks wrap the same idea. Laravel's validation rules, Symfony's Validator constraints and WordPress's sanitize and validate helpers all end with one set of messages per field. Once you understand the error-array approach, any of them is easy to read. Because the returned messages can feed an HTML page, a JSON response or a log line, keeping the validator separate from the code that prints is worth the small effort.

Common mistakes

Common mistakes with validation

Checking a required field with empty()

empty('0') returns true, so a quantity of 0 or a field containing only the digit 0 is reported as missing. Answer 'did the visitor type anything?' by comparing the trimmed string with === ''.

Treating filter_var as a boolean

if (!filter_var('0', FILTER_VALIDATE_INT)) rejects a valid zero, because filter_var returns int(0), which is falsy. Compare with === false, and use FILTER_NULL_ON_FAILURE when you validate booleans.

Stopping at the first error

Putting die() or an early return inside each check makes visitors discover mistakes one at a time and resubmit repeatedly. Run every check and gather the messages in one array.

Trusting the browser's checks

required, maxlength and type=email can be removed in the developer tools, and curl or a script can skip the form entirely. The check in PHP is the real one.

Over-trusting $ in a regex

'/^[a-z0-9_]{3,16}$/' also accepts 'ada_99' followed by a newline. Add the D modifier, or end the pattern with \z.

Best practices

Best practices

  • Validate on the server first and treat browser attributes as a convenience layer.
  • Normalise with trim() before checking, and keep using the cleaned value afterwards.
  • Return one array of messages keyed by field instead of echoing from inside the validator.
  • Check choices such as sort order, country code or status against an allow-list with in_array($value, $allowed, true).
  • Validate type and range together with FILTER_VALIDATE_INT and its min_range and max_range options.

Mini challenge

Mini challenge: validate a product review

Write validateReview(array $input): array for a product review form. It must return an array of messages keyed by field name, and an empty array when the review is acceptable.

  • rating: required whole number from 1 to 5 (FILTER_VALIDATE_INT with min_range and max_range)
  • title: required after trim(), 5 to 60 characters measured with mb_strlen
  • email: must pass FILTER_VALIDATE_EMAIL
  • website: optional, but when given it must be a valid URL whose scheme is http or https
  • Run it on one valid and one invalid review and print every message
review.php
<?php
function validateReview(array $input): array
{
    $errors = [];

    // TODO: read each field with ?? '' and trim() it

    // TODO: rating must be an integer from 1 to 5
    // TODO: title must be 5-60 characters (mb_strlen)
    // TODO: email must be a valid address
    // TODO: website is optional; if present it must be an http or https URL

    return $errors;
}

$reviews = [
    'valid' => [
        'rating' => '5',
        'title' => 'Great keyboard',
        'email' => 'sam@example.com',
        'website' => '',
    ],
    'invalid' => [
        'rating' => '0',
        'title' => 'Meh',
        'email' => 'not-an-email',
        'website' => 'javascript://example.com/%0Aalert(1)',
    ],
];

// TODO: print "accepted", or the field and message of every error, for each review

Expected: The valid review prints accepted. The invalid review prints four messages, one each for rating, title, email and website.

Show hint

Test rating with === false, not with !. For the URL, run filter_var first, then check parse_url($website, PHP_URL_SCHEME) against ['http', 'https'] with in_array(..., true).

Show solution
review.php
<?php
function validateReview(array $input): array
{
    $errors = [];

    $rating = trim((string)($input['rating'] ?? ''));
    $title = trim((string)($input['title'] ?? ''));
    $email = trim((string)($input['email'] ?? ''));
    $website = trim((string)($input['website'] ?? ''));

    $range = ['options' => ['min_range' => 1, 'max_range' => 5]];
    if (filter_var($rating, FILTER_VALIDATE_INT, $range) === false) {
        $errors['rating'] = 'Rating must be a whole number from 1 to 5.';
    }

    $length = mb_strlen($title);
    if ($title === '') {
        $errors['title'] = 'Title is required.';
    } elseif ($length < 5 || $length > 60) {
        $errors['title'] = 'Title must be 5 to 60 characters.';
    }

    if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        $errors['email'] = 'Enter a valid email address.';
    }

    if ($website !== '') {
        $scheme = parse_url($website, PHP_URL_SCHEME);
        $validUrl = filter_var($website, FILTER_VALIDATE_URL) !== false;
        if (!$validUrl || !in_array($scheme, ['http', 'https'], true)) {
            $errors['website'] = 'Website must be an http or https URL.';
        }
    }

    return $errors;
}

$reviews = [
    'valid' => [
        'rating' => '5',
        'title' => 'Great keyboard',
        'email' => 'sam@example.com',
        'website' => '',
    ],
    'invalid' => [
        'rating' => '0',
        'title' => 'Meh',
        'email' => 'not-an-email',
        'website' => 'javascript://example.com/%0Aalert(1)',
    ],
];

foreach ($reviews as $label => $input) {
    $errors = validateReview($input);
    if ($errors === []) {
        echo "$label: accepted\n";
        continue;
    }
    echo "$label: rejected\n";
    foreach ($errors as $field => $message) {
        echo "  $field -> $message\n";
    }
}

Quick quiz 1 / 3

What does this code do with the input "0"? $qty = $_POST['qty']; if (!filter_var($qty, FILTER_VALIDATE_INT)) { $errors[] = 'Quantity must be a whole number.'; }

Quick quiz 2 / 3

A form already has <input type="email" required>. Why must PHP still validate the email?

Quick quiz 3 / 3

With $word = 'မြန်မာ'; (six code points, eighteen UTF-8 bytes), which expression gives 6?

What to remember

  • Validation decides yes or no, sanitization tidies values, and escaping protects each output; none of them replaces the others.
  • Trim first, then check required, length, format and range, collecting every message in an array keyed by field.
  • filter_var returns the filtered value or false (null with FILTER_NULL_ON_FAILURE), so compare with === false.
  • The browser's checks are a convenience; the PHP check on the server is the one that counts.

PHP Security Manual — PHP Documentation Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Form Validation | Thuta Learning