PHP Form Required
The most common form rule: this field is required. Check it server-side; an HTML required attribute is a UX hint, not a guarantee.
Single field
PHP
$name = trim($_POST['name'] ?? '');
if ($name === '') {
$errors['name'] = 'Name is required';
}
Note: don't use empty() for this — it returns true for '0', which is often a valid input.
Loop the required list
PHP
$required = ['name', 'email', 'message'];
foreach ($required as $field) {
if (trim($_POST[$field] ?? '') === '') {
$errors[$field] = ucfirst($field) . ' is required';
}
}
Required + length
PHP
$name = trim($_POST['name'] ?? '');
if ($name === '') {
$errors['name'] = 'Required';
} elseif (mb_strlen($name) < 2) {
$errors['name'] = 'Too short';
} elseif (mb_strlen($name) > 80) {
$errors['name'] = 'Too long';
}
Display the error and keep the value
PHP / HTML
<input
name="name"
value="<?= htmlspecialchars($_POST['name'] ?? '') ?>"
required>
<?php if (isset($errors['name'])): ?>
<p class="error"><?= htmlspecialchars($errors['name']) ?></p>
<?php endif; ?>
Tip: The HTML
required attribute hides bad submissions from your inbox, but a curl request bypasses it. Server checks are the line of defence.Example
Example
<?php
foreach (['name', 'email'] as $field) {
if (empty($_POST[$field])) {
echo "$field is required\n";
}
}
Try it Yourself »
Exercise
Test "really empty" (not "0") with…
if (trim($_POST['name'] ?? '') ===
) {}
Two quote characters; the empty string.
Discussion
Loading…