Summary: in this tutorial, you’ll learn about PHP form validation, how to validate form data, and how to show error messages if the user inputs are invalid.
Introduction to PHP form validation
When processing a form, it’s critical to validate user inputs to ensure that the data is in a valid format.
There are two types of validations: client-side & server-side:
The client-side validation is performed in the web browsers of the users. To validate data at the client side, you can use HTML5 validation or JavaScript. The client-side validation aims to assist legitimate users in entering data in the valid format before submitting it to the server.
However, client-side validation doesn’t prevent malicious users from submitting data that can potentially exploit the application.
The server-side validation validates data in the web server using PHP. To validate data in PHP, you can use the filter_var()
and filter_input()
functions.
PHP form validation example
We’ll build an email subscription form that includes a validation feature. The form has the name and email input elements and a submit button:
If you don’t enter the name and/or email and click the subscribe button, the form will show the error messages. Also, if you enter an invalid email address, the form will show a different error message.
Notice that we don’t use the client-side validation for this form to make it easier to test. In practice, you should also use client-side validation.
Organize the directory and files
First, create a file and directory structure as follows:
.
├── css
│ └── style.css
├── inc
│ ├── get.php
│ ├── post.php
│ ├── header.php
│ ├── footer.php
│ └── .htaccess
└── index.php
Code language: plaintext (plaintext)
The following table describes the purpose of each file:
File | Directory | Description |
---|---|---|
index.php | . | Contain the main logic of the form |
header.php | inc | Contain the header code |
footer.php | inc | Contain the footer code |
get.php | inc | Contain the email subscription form |
post.php | inc | Contain the code for handling form submission |
style.css | css | Contain the CSS code |
header.php
The following shows the header.php
file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<title>Subscribe</title>
</head>
<body>
<main>
Code language: HTML, XML (xml)
The header.php
file link to the style.css
file in the css
directory.
footer.php
And the footer.php
only contains the enclosing tags that correspond to the opening tags in the header.php
file:
</main>
</body>
</html>
Code language: HTML, XML (xml)
index.php
The index.php
file contains the main logic of the form:
<?php
require __DIR__ . '/inc/header.php';
$errors = [];
$inputs = [];
$request_method = strtoupper($_SERVER['REQUEST_METHOD']);
if ($request_method === 'GET') {
// show the form
require __DIR__ . '/inc/get.php';
} elseif ($request_method === 'POST') {
// handle the form submission
require __DIR__ . '/inc/post.php';
// show the form if the error exists
if (count($errors) > 0) {
require __DIR__ . '/inc/get.php';
}
}
require __DIR__ . '/inc/footer.php';
Code language: HTML, XML (xml)
How the index.php
works.
First, load code from both header.php
and footer.php
files using the require
construct at the top and bottom of the file to generate the header and footer.
Second, define the $errors
array to store error messages and the $inputs
array to store the entered form values. If an input element has invalid data, the index.php
will show the entered value stored in the $inputs
.
Third, show the form if the HTTP request method is GET by loading the get.php file. Once you enter the
Finally, load the code in the post.php
to handle the form submission if the HTTP request method is POST. If the form has any errors, the $errors
will not empty. In this case, show the form again with the error messages stored in the $errors
array and entered values stored in the $inputs
arrays.
get.php
The get.php
file contains the form:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
<header>
<h1>Get FREE Updates</h1>
<p>Join us for FREE to get email updates!</p>
</header>
<div>
<label for="name">Name:</label>
<input type="text" name="name" id="name" placeholder="Full Name" value="<?php echo $inputs['name'] ?? '' ?>" class="<?php echo isset($errors['name']) ? 'error' : '' ?>">
<small><?php echo $errors['name'] ?? '' ?></small>
</div>
<div>
<label for="name">Email:</label>
<input type="text" name="email" id="email" placeholder="Email Address" value="<?php echo $inputs['email'] ?? '' ?>" class="<?php echo isset($errors['email']) ? 'error' : '' ?>">
<small><?php echo $errors['email'] ?? '' ?></small>
</div>
<button type="submit">Subscribe</button>
</form>
Code language: HTML, XML (xml)
How the get.php
works.
- First, fill the name and email input elements with the entered values stored in the
$inputs
array only if these values exist. - Second, show the error messages stored in the
$errors
array if they exists.
post.php
The following shows the code of the post.php
file. The post.php
validates the form data using the filter_input()
and filter_var()
functions.
<?php
const NAME_REQUIRED = 'Please enter your name';
const EMAIL_REQUIRED = 'Please enter your email';
const EMAIL_INVALID = 'Please enter a valid email';
// sanitize and validate name
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$inputs['name'] = $name;
if ($name) {
$name = trim($name);
if ($name === '') {
$errors['name'] = NAME_REQUIRED;
}
} else {
$errors['name'] = NAME_REQUIRED;
}
// sanitize & validate email
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$inputs['email'] = $email;
if ($email) {
// validate email
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if ($email === false) {
$errors['email'] = EMAIL_INVALID;
}
} else {
$errors['email'] = EMAIL_REQUIRED;
}
?>
<?php if (count($errors) === 0) : ?>
<section>
<h2>
Thanks <?php echo htmlspecialchars($name) ?> for your subscription!
</h2>
<p>Please follow the steps below to complete your subscription:</p>
<ol>
<li>Check your email (<?php echo htmlspecialchars($email) ?>) - Find the message sent from [email protected]</li>
<li>Click to confirm - Click on the link in the email to confirm your subscription.</li>
</ol>
</section>
<?php endif ?>
Code language: HTML, XML (xml)
How it works.
First, define some constants to store the error messages. In a real-world application, you can store all the messages in a separate file:
const NAME_REQUIRED = 'Please enter your name';
const EMAIL_REQUIRED = 'Please enter your email';
const EMAIL_INVALID = 'Please enter a valid email';
Code language: JavaScript (javascript)
Second, sanitize and validate the name using the filter_input() function. If the name is empty, add an error message to the $errors
array.
// sanitize and validate name
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$inputs['name'] = $name;
if ($name) {
$name = trim($name);
if ($name === '') {
$errors['name'] = NAME_REQUIRED;
}
} else {
$errors['name'] = NAME_REQUIRED;
}
Code language: PHP (php)
Third, sanitize and validate email using the filter_input()
and filter_var()
functions. If the email is empty or invalid, add the corresponding error message to the $errors
array.
// sanitize & validate email
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$inputs['email'] = $email;
if ($email) {
// validate email
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if ($email === false) {
$errors['email'] = EMAIL_INVALID;
}
} else {
$errors['email'] = EMAIL_REQUIRED;
}
Code language: PHP (php)
Finally, if the form has no error, show the confirmation message:
<?php if (count($errors) === 0) : ?>
<section>
<h2>
Thanks <?php echo htmlspecialchars($name) ?> for your subscription!
</h2>
<p>Please follow the steps below to complete your subscription:</p>
<ol>
<li>Check your email (<?php echo htmlspecialchars($email) ?>) - Find the message sent from [email protected]</li>
<li>Click to confirm - Click on the link in the email to confirm your subscription.</li>
</ol>
</section>
<?php endif ?>
Code language: HTML, XML (xml)
To complete the form, you can save the contact data to a database or call an API of an email marketing service to add the contact to your list.
Summary
- Use
filter_input() and filter_var()
functions to validate and sanitize data.