Skip to content

PHP Tutorial Forms and User Input

Required Fields

Lesson 138 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

HTML can mark a field required, and the browser will stop an empty submission. That is a convenience for the user, not security. Anyone can turn it off or send a request without a browser. PHP must check again.

index.html
HTML
<input type="text" name="name" required>

Check on the server

index.php
PHP
<?php
$_POST = ["name" => "   ", "email" => "isha@example.com"];

$errors = [];

$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");

if ($name === "") {
    $errors[] = "Name is required.";
}

if ($email === "") {
    $errors[] = "Email is required.";
}

print_r($errors);
Output
OUTPUT
Array
(
    [0] => Name is required.
)

Two details: trim() makes a field with only spaces count as empty, and the comparison with "" keeps a real "0" valid.

Do not use empty() for text

empty("0") is true, so a name of "0" or a quantity of "0" would be rejected. Compare with "" instead.

index.php
PHP
<?php
var_dump(empty("0"));
var_dump("0" === "");
Output
OUTPUT
bool(true)
bool(false)

Check many required fields at once

index.php
PHP
<?php
function missingFields(array $data, array $required): array
{
    $missing = [];

    foreach ($required as $field) {
        $value = $data[$field] ?? "";

        if (!is_string($value) || trim($value) === "") {
            $missing[] = $field;
        }
    }

    return $missing;
}

$input = ["name" => "Isha", "email" => "", "message" => "Hi"];

print_r(missingFields($input, ["name", "email", "message", "phone"]));
Output
OUTPUT
Array
(
    [0] => email
    [1] => phone
)

Required checkboxes and files

  • A required checkbox (for example “I agree to the terms”) is valid when isset($_POST["agree"]).
  • A required file upload is checked through $_FILES. See File Uploads.

Tell the user which field is missing

An error message that says only “Something is wrong” is not helpful. Name the field, say what to do and show the message next to the field. Validation Errors shows how.

info
Both checks, always
Keep the HTML required attribute, because it gives instant feedback. Keep the PHP check too, because it protects your data.