How to Validate Form Input in PHP
Validating user input is a cornerstone of secure and reliable web applications. In PHP, proper validation protects you from malformed data, prevents security vulnerabilities like SQL injection and XSS, and improves the overall user experience. This article walks you through the most effective techniques, from built‑in filters to custom regular expressions, and shows how to handle errors gracefully.
Why Validate Form Input?
Before you store or process any data, you must ensure it meets the expected format and constraints. Validation helps you:
- Guard against malicious payloads (SQL injection, cross‑site scripting, etc.).
- Maintain data integrity in databases.
- Provide clear feedback to users, reducing frustration.
- Lower server load by rejecting bad requests early.
Basic Validation Workflow
A typical validation flow in PHP looks like this:
- Collect raw
$_POSTor$_GETdata. - Trim and sanitize the input.
- Validate each field against its rules.
- Collect error messages for any failed checks.
- If there are no errors, process the data (e.g., insert into a database).
Key PHP Functions for Validation
1. filter_var() and filter_input()
PHP’s filter extension provides a fast, readable way to validate common data types.
<?php
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1, 'max_range' => 120]
]);
$url = filter_input(INPUT_POST, 'website', FILTER_VALIDATE_URL);
?>
2. Regular Expressions with preg_match()
When you need more granular control (e.g., custom usernames), regular expressions are the tool of choice.
<?php
$username = $_POST['username'] ?? '';
$pattern = '/^[a-zA-Z0-9_]{5,20}$/';
if (!preg_match($pattern, $username)) {
$errors['username'] = 'Username must be 5‑20 characters and contain only letters, numbers, or underscores.';
}
?>
3. Sanitizing Functions
Sanitization removes unwanted characters but does not guarantee the data is valid. Use it together with validation.
<?php
$comment = filter_input(INPUT_POST, 'comment', FILTER_SANITIZE_STRING);
$comment = trim($comment);
?>
Common Validation Scenarios
Validating an Email Address
<?php
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Please enter a valid email address.';
}
?>
Validating a URL
<?php
$url = filter_input(INPUT_POST, 'website', FILTER_SANITIZE_URL);
if (!filter_var($url, FILTER_VALIDATE_URL)) {
$errors['website'] = 'Please provide a valid URL.';
}
?>
Validating an Integer Range
<?php
$quantity = filter_input(INPUT_POST, 'quantity', FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1, 'max_range' => 1000]
]);
if ($quantity === false) {
$errors['quantity'] = 'Quantity must be a number between 1 and 1000.';
}
?>
Validating a Date (YYYY‑MM‑DD)
<?php
$date = $_POST['date'] ?? '';
$dt = DateTime::createFromFormat('Y-m-d', $date);
if (!$dt || $dt->format('Y-m-d') !== $date) {
$errors['date'] = 'Enter a valid date in YYYY‑MM‑DD format.';
}
?>
Handling Errors and Displaying Feedback
Collect errors in an associative array and repopulate the form fields so users don’t lose their input.
<?php
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// ...validation logic...
if (empty($errors)) {
// Process data (e.g., insert into DB)
}
}
?>
In the HTML part of the form, you can echo the error messages next to each field:
<label for="email">Email:</label>
<input type="email" name="email" id="email" value="<?= htmlspecialchars($email ?? '') ?>">
<?php if (!empty($errors['email'])): ?>
<span class="error"><?= $errors['email'] ?></span>
<?php endif; ?>
Security Considerations
- Never trust client‑side validation alone. Always repeat validation on the server.
- Use
prepared statementsor PDO with bound parameters to avoid SQL injection. - Escape output with
htmlspecialchars()when echoing user data back to the page. - Limit the size of uploaded files and check MIME types.
Best‑Practice Checklist
- Trim whitespace from all inputs.
- Sanitize before validation when appropriate.
- Use
filter_var()for standard data types. - Apply regular expressions for custom patterns.
- Validate numeric ranges and dates with built‑in PHP classes.
- Store error messages in an array and display them next to the relevant fields.
- Never echo raw input; always escape with
htmlspecialchars(). - Use prepared statements for any database interaction.
- Log validation failures for debugging (but never expose internal details to users).
Conclusion
Effective form validation in PHP combines built‑in filters, regular expressions, and careful sanitization. By following the workflow and best‑practice checklist above, you’ll protect your application from common security threats while delivering a smooth user experience. Remember: validation is a continuous process—keep your rules up to date as your application evolves.