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.
<input type="text" name="name" required>
Check on the server
<?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);
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.
<?php
var_dump(empty("0"));
var_dump("0" === "");
bool(true)
bool(false)
Check many required fields at once
<?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"]));
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.
Both checks, always
required attribute, because it gives instant feedback. Keep the PHP check too, because it protects your data.