Category: PHP5

Added: 15th of December 2015

Viewed: 1342 times

How to validate a form using PHP5

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(!eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $_POST['email_address'])) { $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="">";

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>";
}

?>

Other Tips & Tutorials

PHP5

Convert all characters to Upper or Lower case in PHP5

Posted: 7th of October 2020

Views: 453

PHP5

Get the day of the week for a specified date using PHP5

Posted: 17th of January 2016

Views: 2084

PHP5

How to upload files larger than 2MB using PHP5

Posted: 14th of January 2016

Views: 2261

PHP5

Preserve line breaks in PHP. nl2br function

Posted: 21st of December 2015

Views: 4836

PHP5

Convert a Unix timestamp to date and time using PHP

Posted: 18th of December 2015

Views: 2406

PHP5

How to validate a form using PHP5

Posted: 15th of December 2015

Views: 1342

PHP5

Count the number of elements in a PHP array using the count() function

Posted: 15th of December 2015

Views: 1211

PHP5

Pass ampersand through query strings in URL using PHP5

Posted: 27th of November 2015

Views: 2687