This article was updated and rechecked on 1st of December 2023
Logo 468x120

Category: PHP7

Added: 15th of December 2015

Updated On: 1st of December 2023

Viewed: 2,773 times


How to validate a form using PHP7

It is important to validate user input with all your forms in .php. It will ensure that your data remains consistent.

The following .php code displays a simple contact form, but also displays an error message on the same page if the user fails to complete any of the form fields.

There are other ways to validate forms using HTML5, or Javascript, it's all down to personal preference.

Open up your text editor, copy and paste the code below and save the file as form.php then upload it to your local or remote server to test the script.

<?php
if (!$_POST['submit'])
{
form();
} else {
if (empty($_POST['first_name'])) { $error0='<br>First Name'; }

if (empty($_POST['surname'])) { $error1='<br>Surname'; }

if (!filter_var($_POST['email_address'], FILTER_VALIDATE_EMAIL)) { $error2='<br>Valid e-mail address'; }

$error_messages = $error0.$error1.$error2;
if ($error_messages)
{
echo "Please ensure the following fields are completed before submitting your form:<strong>". $error_messages ."</strong><br><br>";

form();

} else {

echo "Thank you for completing the form. Please <a href='form.php'>click here</a> to contine....";
}
}
?>

<?php
function form()
{
echo "<form method='post' action='". htmlspecialchars($_SERVER[" PHP_SELF "]) ."'>";

echo "First Name: <input type='text' name='first_name' size='35' value='" . $_POST['first_name'] . "'><br>";

echo "Surname: <input type='text' name='surname' size='35' value='". $_POST['surname'] . "'><br>";

echo "Email Address: <input type='text' name='email_address' size='35' value='". $_POST['email_address'] . "'><br>";

echo "<input type='submit' name='submit' value='Submit Form'>";

echo "</form>";
}
?>