Hello, my name is Pieter!

I build web applications and craft user interfaces.

PHP Form Validation

Forms are used in many ways: there are Sign Up-forms, Log In-forms, Contact-forms, Image Upload forms. These are very commonly used, but validation is often forgotten. Under the motto: Never trust your users, it's absolutely important to validate the user's input for two reasons:

  1. The user might be trying to hack your website or delete your MySQL databases. I do not think you want this.
  2. The user might have made a mistake and so you want him to correct it.

In both ways, server-side validation is a good way to protect your databases from hackers and mistakes.
Here is a little demo and you can download the .zip-file here.

Why server-side and not client-side validation?

Some people prefer server-side, some people prefer client-side. I personally do prefer server-side because:

So, I've written a little validation script in PHP. It's a basic function using mostly regular expressions to check if user input is valid. Thanks to Nettuts for some regular expressions

At the moment, it is able to check if the following are valid:

Additionally, it is able to handle required & not required input fields.

I threw all of this in a little function so it's reusable for later projects. I'd like to share the function with you.
Click here to download.

Usage

Now, how do we use this? Simple. First of all we have to include our function file in the page that handles the form. <?php require_once 'validate.php'; ?>

Next, we have to validate the input and compile the errormessage. <?php
if(isset($_POST['submit'])) {
// If submit button is clicked.
$errormsg = validate($_POST['username'], "username");
$errormsg.= validate($_POST['password'], "password");
$errormsg.= validate($_POST['email'], "email");
$errormsg.= validate($_POST['url'], "url", "not_required");
$errormsg.= validate($_POST['date'], "date", "not_required");
if (empty ($errormsg))
// no error message? go on and do the form action
{
// Execute form here
echo "Everything went good!";
}
else
{
echo $errormsg;
}
}
?>

The validate()-function has three parameters:

Additional: when an error is given, don't make the user lose his previously entered information

This is a simple piece of code adding a big value to the usability of your forms. <input type="text" name="username" value="<?php if (isset($_POST['username'])) {echo $_POST['username'];} ?>" /> The trick: it checks if the $_POST is set for the input, if so, it displays the current value.