Advanced PHP Form Input Validation to Check User Inputs

PHP form input validation is what separates amateur and professional PHP developers. A professional PHP developer validates data for both security and correctness of the data entered. Keep reading to learn how to validate user input to your forms.

Web form processing is one of the most important tasks any website can do to process customer-related information. PHP server side scripting offers a variety of solutions for accepting and processing data inputs from any web form.

However, a lot of website forms do not have input validation. "Input validation" is the process of double checking form data input to ensure they are the correct data the server needs to process. Without proper form input validation, the web server and database will process or store the wrong information.

A classic example concerns forms that ask for an email address. If you do not validate the input data, malicious users can enter other types of characters into the form to hack your MySQL database. Serious website security issues, such as MySQL injection and malware injection, result from improper form input validation.

In this article, we will aim to provide PHP solutions which will validate the most common fields used in  website development:

  • Validating alphanumeric input — This type of input is commonly used for usernames and passwords. "Alphanumeric" means the variable can contain numbers and letters of the alphabet only.

  • Validating numeric input — Often, web forms ask for numbers. These can be phone numbers or credit card numbers. Other important applications include asking for a birth date, numbers would be entered by the user for the day, month and year of birth. That’s numerical data.

  • Validating names — This kind of validation should check for letters of the alphabet only; user input should not contain numbers.

  • Validating email address — The email address is most commonly asked for in a web form. It’s particularly common for a log-in page.

  • Validating for empty fields — Often, certain fields must be filled on an online form, and the user is not permitted to leave them blank. 

{mospagebreak title=Validating Email Addresses}

Let’s start by defining the email address. It contains two sections: the local part and the domain name. For example, in the email address Testuser1@xyz.com, Testuser1 is the local part of the email address while xyz.com is the domain name. Below are the specifications necessary for checking email address validity.

For the local part of the email address, a form should only permit:

  • Uppercase and lowercase English letters (a-z, A-Z)
  • The digits 0 through 9
  • The characters  ! # $ % & ‘ * + – / = ? ^ _ ` { | } ~
  • The character . provided that it is not the first nor last character; nor may it appear two or more times consecutively.

(Source: RFC Specification: http://en.wikipedia.org/wiki/E-mail_address )

The domain name half of the email address should be a valid domain. Validating an email address is very challenging, especially if you have a version of PHP below 5, because it requires a long Reg Ex syntax using either the ereg or pregmatch function. Luckily, with the release of PHP 5, you can easily validate email addresses using the filter_var / FILTER_VALIDATE_EMAIL function.

This will automatically check versus RFC specifications stated above. The last thing you need to check to find out if the email address is valid is whether the domain name given is valid. There are lots of approaches to this, including checking to see if the domain name has mail exchange records (MX) or A records.

You can find great resources relating to this task at: http://www.devshed.com/c/a/PHP/Email-Address-Verification-with-PHP/

{mospagebreak title=Validating Domains for Email Addresses}

The function responsible for checking to see if the domain has associated mail exchange records is checkdnsrr () . However, this function is not available on the Windows platform and can cause validation issues for the domain name. It needs to have a Windows-compatible checkdnsrr function. The script below is tested to work in Windows XAMPP, but it is not guaranteed to work in all server platforms.

<?php

// PHP email validation script by Codex M for PHP 5 and compatible with Windows platform.

//This script will accept email address and validate it according to RFC specifications as well as check DNS records for validity.

//Then if found valid will store the email to MySQL database.

//connect to MySQL database

$username = "mysqlusernamehere";

$password = "mysql password here";

$hostname = "localhost";

$table = "email";

$database = "email";

//connection to the database

$dbhandle = mysql_connect($hostname, $username, $password)

or die("Unable to connect to MySQL");

//select a database to work with

$selected = mysql_select_db($database,$dbhandle)

or die("Could not select $database");

if (!$_POST['submit'])

{

//form not submitted

?>

<form action="<?php echo $SERVER['PHP_SELF']; ?>"

method="post">

Email Address:

<br />

<input type="text" name="email" size="50">

<br /><br />

<input type="submit" name="submit" value="Test email according to RFC Specifications and DNS MX records">

</form>

<?php

}

else

{

//form submitted

//check email field

if (!isset($_POST['email']) || trim($_POST['email']) == "")

{

die (‘ERROR: Enter email’);

}

else

{

$email =$_POST['email'];

//sanitize for illegal characters

$email = mysql_real_escape_string(stripslashes($email));

//check domain name if it exist

$domainname= explode("@",$email);

$checkdomain= $domainname[1];

//Codex-m improve the Windows compatible checking Checkdnsrr function by Hamish Milne

//Start of MX validation

function checkdnsrr($checkdomain, $type=’mx’){

$res=explode("n",strstr(shell_exec(‘nslookup -type=’.$type.’ ‘.escapeshellarg($checkdomain).’ 4.2.2.3′),"nn"));

if($res[2]){

return TRUE;

}else{

return FALSE;

}

}

function dns_check_record($checkdomain, $type=’mx’){

return checkdnsrr($checkdomain, $type);

}

$result = dns_check_record($checkdomain, $type=’mx’);

}

//End of MX validation

if((!(filter_var($email, FILTER_VALIDATE_EMAIL))) ||(!($result==1)))

{

echo $email.’ is NOT a valid email address';

echo ‘<br />';

echo ‘<a href="http://localhost/testemail.php">Try again</a>';

}

else

{

echo $email.’ is a valid email address';

mysql_query("INSERT INTO `email` (`email`) VALUES(‘$email’)")

or die(mysql_error());

echo ‘<br />';

echo ‘<a href="http://localhost/testemail.php">Try again</a>';

}

}

?>

{mospagebreak title=Validating Alphanumeric, Numeric and Alphabetic Input}

Alphanumeric input is common in web forms. Most usernames and passwords are formatted using alphanumeric data types.

Luckily, PHP provides a function for checking alphanumeric characters. This function is called:

ctype_alnum($stringtotest)

It is important to note that security issues such as MySQL injection can only be corrected with the mysql_real_escape_string(stripslashes($stringtotest)) function.

IMPORTANT: Before inputting or querying a MySQL database, it is highly advisable to use the above escape function for your safety.

Also, validating empty fields can be done using:

if (!isset($_POST['email']) || trim($_POST['email']) == "")

as illustrated in the PHP email validation script. However, there are a lot of ways to do this, such as the empty() function, which will be illustrated below.

Numeric input only can be validated by: ctype_digit($stringtotest) and lastly, alphabet characters (alphabet input only) can be validated using: ctype_alpha($stringtotest)

Below is a sample script illustrating the above PHP data type validation function in action. It also prevents MySQL injection and reports all validation errors at once:

<?php

//The script will test various datatypes such as alphanumeric, numeric and alphabet characters

//This also checks if the data entered is not blank and prevent mysql injection.

//If the data entered is clean it will be save to the MySQL database

//connect to MySQL database

$username = "root";

$password = "xxxxx";

$hostname = "localhost";

$table = "datatypevalidation";

$database = "email";

//connection to the database

$dbhandle = mysql_connect($hostname, $username, $password)

or die("Unable to connect to MySQL");

//select a database to work with

$selected = mysql_select_db($database,$dbhandle)

or die("Could not select $database");

if (!$_POST['submit'])

{

//form not submitted

?>

<form action="<?php echo $SERVER['PHP_SELF']; ?>"

method="post">

Username(alphabet characters only e.g John):

<br />

<input type="text" name="username" size="50">

<br /><br />

Password (alphanumeric characters only e.g John458):

<br />

<input type="text" name="password" size="50">

<br /><br />

Birthday (numeric characters only e.g 12011986 for December 1, 1986):

<br />

<input type="text" name="birthday" size="50">

<br /><br />

<input type="submit" name="submit" value="Submit and validate data entered">

</form>

<?php

}

else

{

//array to store the error messages

$mistakes = array();

//validate username field

$username = trim($_POST['username']);

If (empty($username) || (!(ctype_alpha($username))))

{

$mistakes[] = ‘Your username is either empty or Enter only ALPHABET characters.';

}

else

{

//accept username entry and sanitize it

$username = mysql_real_escape_string(stripslashes($username));

}

//validate password field

$password = trim($_POST['password']);

If (empty($password) || (!(ctype_alnum($password))))

{

$mistakes[] = ‘Your password is either empty or Enter only ALPHANUMERIC characters ‘;

}

else

{

//accept password entry and sanitize it

$password = mysql_real_escape_string(stripslashes($password));

}

//validate birthday field

$birthday = trim($_POST['birthday']);

If (empty($birthday) || (!(ctype_digit($birthday))))

{

$mistakes[] =’Your birthday is either empty or Enter only NUMERIC characters';

}

else

{

//accept birthday data and sanitize it

$birthday = mysql_real_escape_string(stripslashes($birthday));

}

if (sizeof($mistakes) > 0)

{

echo "<ul>";

foreach ($mistakes as $errors)

{

echo "<li>$errors</li>";

}

echo "</ul>";

echo ‘<br />';

echo "Press back button to CORRECT the entry";

mysql_close($dbhandle);

die ();

}

else

{

//save to database

mysql_query("INSERT INTO `datatypevalidation` (`username`,`password`,`birthday`) VALUES(‘$username’,’$password’,’$birthday’)")

or die(mysql_error());

echo "SUCCESS! Thanks for the data you entered, it is already save to the database";

echo ‘<br />';

echo "This is your copy:";

echo ‘<br />';

echo ‘<br />';

echo "Username:".’ ‘.$username;

echo ‘<br />';

echo "Password:".’ ‘.$password;

echo ‘<br />';

echo "Birthday:".’ ‘.$birthday;

echo ‘<br />';

echo ‘<br />';

echo ‘<a href="http://localhost/datatypevalidation.php">Try entering another sets of data</a>';

mysql_close($dbhandle);

}

}

?>

The great thing about this script is that it will validate each field against the defined standard (if it is alphabetic, alphanumeric or numeric entry), and then display all validation errors as a list to inform the user what has been entered incorrectly.

In this way, the form is more user-friendly, and at the same time, it ensures that all data entered will be in the correct format and MySQL injection will be prevented.

If you would like to download the script, refer to the author website: http://www.php-developer.org/ . Thanks.

[gp-comments width="770" linklove="off" ]

chat