PHP Form Validation
Receiving form data is easy; trusting it is not. Anyone can send any bytes to your script — not only through your nicely designed form, but also with tools like curl. Validation means checking that every value has the shape you expect before you use it, and telling the user clearly what went wrong when it does not.
Client-side vs server-side
HTML attributes such as required, type="email" and maxlength give quick feedback in the browser, but they are only a convenience. They can be removed with the developer tools in seconds.
| Check | Where it runs | Can be bypassed? | Purpose |
|---|---|---|---|
| HTML attributes / JavaScript | Browser | Yes | Fast feedback for honest users |
| PHP validation | Server | No | The real security boundary |
Note: Always validate on the server, even if the browser already did.
A form to validate
<form method="post" action="contact.php">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
Website: <input type="text" name="website">
Age: <input type="text" name="age">
Message: <textarea name="message"></textarea>
<button>Send</button>
</form>Step 1: clean the input
A small helper that trims surrounding whitespace is a common first step. Keep the raw value for validation and escape it only when you output it — escaping too early corrupts data you store in a database.
<?php
function clean(string $value): string
{
return trim($value);
}
$_POST = ['name' => " Linh Nguyen \n", 'message' => ' Hi <there> '];
$name = clean($_POST['name'] ?? '');
$message = clean($_POST['message'] ?? '');
echo "[" . $name . "]" . PHP_EOL;
echo "[" . htmlspecialchars($message) . "]" . PHP_EOL;[Linh Nguyen]
[Hi <there>]
Step 2: check each field
Each rule produces an error message stored in an $errors array keyed by field name. If the array is empty at the end, the form is valid.
| Field | Rule | PHP tool |
|---|---|---|
| name | letters, spaces, ' and - only |
preg_match() |
| a valid address | filter_var($v, FILTER_VALIDATE_EMAIL) |
|
| website | optional, but a valid URL if given | filter_var($v, FILTER_VALIDATE_URL) |
| age | whole number 13–120 | filter_var($v, FILTER_VALIDATE_INT, [...]) |
| message | 10–500 characters | mb_strlen() |
<?php
function validateContact(array $in): array
{
$errors = [];
$name = trim($in['name'] ?? '');
if (!preg_match("/^[\p{L} '-]+$/u", $name)) {
$errors['name'] = 'Only letters, spaces, apostrophes and hyphens are allowed.';
}
$email = trim($in['email'] ?? '');
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors['email'] = 'Please enter a valid email address.';
}
$website = trim($in['website'] ?? '');
if ($website !== '' && filter_var($website, FILTER_VALIDATE_URL) === false) {
$errors['website'] = 'The website must be a full URL such as https://example.test.';
}
$age = filter_var($in['age'] ?? '', FILTER_VALIDATE_INT,
['options' => ['min_range' => 13, 'max_range' => 120]]);
if ($age === false) {
$errors['age'] = 'Age must be a whole number between 13 and 120.';
}
$len = mb_strlen(trim($in['message'] ?? ''));
if ($len < 10 || $len > 500) {
$errors['message'] = "Message must be 10-500 characters (got $len).";
}
return $errors;
}
$_POST = [
'name' => 'R2-D2 <bot>',
'email' => 'r2d2@',
'website' => 'tatooine',
'age' => '9',
'message' => 'Beep!',
];
foreach (validateContact($_POST) as $field => $msg) {
echo str_pad($field, 8) . "| $msg" . PHP_EOL;
}name | Only letters, spaces, apostrophes and hyphens are allowed.
email | Please enter a valid email address.
website | The website must be a full URL such as https://example.test.
age | Age must be a whole number between 13 and 120.
message | Message must be 10-500 characters (got 5).
Step 3: react to the result
If there are errors, show the form again with the messages and the user's previous values (escaped!) so they don't have to retype everything. If not, process the data and usually redirect to a "thank you" page so refreshing doesn't resubmit the form (the Post/Redirect/Get pattern).
<?php
function validateSignup(array $in): array
{
$errors = [];
if (filter_var($in['email'] ?? '', FILTER_VALIDATE_EMAIL) === false) {
$errors['email'] = 'Invalid email.';
}
if (strlen($in['password'] ?? '') < 8) {
$errors['password'] = 'Password needs at least 8 characters.';
}
return $errors;
}
$requests = [
['email' => 'ana@example.test', 'password' => 'short'],
['email' => 'ana@example.test', 'password' => 'long-enough-1'],
];
foreach ($requests as $i => $post) {
$errors = validateSignup($post);
echo "Request " . ($i + 1) . ": ";
if ($errors) {
echo "redisplay form with " . count($errors) . " error(s)" . PHP_EOL;
echo ' <input name="email" value="' . htmlspecialchars($post['email']) . '">' . PHP_EOL;
foreach ($errors as $msg) {
echo " * $msg" . PHP_EOL;
}
} else {
echo "saved, then: Location: /thanks.php" . PHP_EOL;
}
}Request 1: redisplay form with 1 error(s)
<input name="email" value="ana@example.test">
* Password needs at least 8 characters.
Request 2: saved, then: Location: /thanks.php
Tip: Never re-fill a password field after a failed submission, and never print a password back to the page.
Test yourself
Why is HTML required or type="email" not enough to validate a form?
- Browsers ignore it
- It can be bypassed, so the server must validate too
- PHP removes those attributes
- It only works with GET
What does filter_var('abc', FILTER_VALIDATE_EMAIL) return?
null''false0
When is the best time to call htmlspecialchars() on user input?
- Right after reading
$_POST - Before saving to the database
- When the value is output into HTML
- Never