Posts Tagged ‘PHP Form Validation’

Jan 20 PHP Form Validation Posted at 9:59 pm | 1 Comment »

Want to learn more about Web Technology? Check out the new HTMLCenter Blog!

The validation of data that has been entered in a form is necessary in most cases. Why is important? For example, what good is holding a contest or sweepstakes if you can’t notify the winner, because he or she entered an invalid telephone number or an incorrect address. What good is having a mailing list if the e-mail addresses on it aren’t verified, and your mailing list just bounces back to you without reaching the subscribers and target audience.

Validating form entries saves you time and more importantly, it can save you money. And since somebody embossed the slogan “Time is money!”, this should be very important for your web site!

Well when should we validate? There are two types of validation; client side and server side.

For reference, client side means that you are depending on what browser the user is currently using. On the client side, validation is performed using JavaScript. And that can be very tricky, because some users turn off JavaScript support in their browsers before they even come to your site. If you encounter of one those users, client side validation won’t help you much if you try to verify data from a form because your JavaScript code will not be executed or interpreted by the browser, means you are back to square 1. Remember, the winner of your competition entered a wrong address.

This is where server side validation comes in handy. It will always work, no matter what. Of course assuming that you have access to the technology on your server. Server side validation can be done with Perl, PHP, ASP, ColdFusion, JSP and almost any other scripting language. For this tutorial, I’ll use PHP. A quite popular and easy to master server side scripting language.


Now that you know the differences between client side and server side validation, you might ask, “Why use client side validation at all?” The reason is, that especially high traffic web sites, should seize the opportunity to take off the load of the server and distribute it to the client browser. This means that if you can verify the content of a field before it is submitted and processed by the server, it makes sense to do so. And there is a user friendly side of it as well. Since most people assume that once they have clicked the submit button on a form, the process is over. A nifty popup explaining what is missing or incorrect, improves their chance of entering correct data into the form. Who wants to miss out on that lottery jackpot just because he or she forgot to verify the data they entered on an online entry form.

Enough explanation, now let’s examine the code. We’ll start with server side validation.

Server side validation with PHP

For one of my last projects, I decided to use the following validation. I checked with JavaScript if anything was inserted in a field and the used server side validation to figure out if the content was ok.

Let’s start off with my favorite server side validation. I am verifying a field for numbers only (e.g. a zip code), numbers and spaces (e.g. a telephone number), etc. Here’s my setup; I have a form.php and a error.php.

form.php

<html>
<head> ...</head>
<body>
<form action="error.php" method="post">
<table>
<tr><td>Your name:</td><td>
<input type="text" name="your_name"></td></tr>
<tr><td>Your phone:</td><td>
<input type="text" name="your_phone"></td></tr>
<tr><td>Zip code:</td><td>
<input type="text" name="your_zip"></td></tr>
</table> <br>
<input type="submit">
</form>
</body>
</html>

Pretty easy, eh? The table is not necessary, but it helps to make the form look nice.

error.php

<?php
extract($_POST);
/* Validation */

function check_field1($field_name_1)
{
  if(!preg_match("/[^a-zA-Z0-9\.\-\Ä\ä\Ö\ö\Ü\ü\
   ]+$/s",$field_name_1))
    return TRUE;
  else
    return FALSE;
}

function check_field2($field_name_2)
{
  if(!preg_match("/[^0-9\ ]+$/",$field_name_2))
    return TRUE;
  else
    return FALSE;
}

function check_field3($field_name_3)
{
  if(!preg_match("/[^0-9]+$/ ",$field_name_3))
    return TRUE;
  else
    return FALSE;
}

/* Validation */

$error=0; // check up variable

/* get it checking */

if(!check_field1($your_name))
{
  echo "Illegal input $your_name in 'your_name'";
  $error++; // $error=$error+1;
}
if(!check_field2($your_phone))
{
  echo "Illegal input $your_phone in 'your_phone'";
  $error++;
}
if(!check_field3($your_zip))
{
  echo "Illegal input $your_zip in 'your_zip'";
  $error++;
}

if($error == 0)
{
  echo
  "
  The data you entred was correct, thank you!<p>
  Your data:<br>
  Your name: $your_name<br>
  Your phone: $your_phone<br>
  ZIP code: $your_zip
  ";
}else{
  echo "Number of errors: $error";
}

?>

Now for the code explanation. First of all, we have three functions to do the error checking. All three utilize a PHP function called preg_match (http://www.php.net/manual/en/function.preg-match.php). We call the function, tell it what field to check and when the entered data matches the string it looks by it returns true, or false if it doesn’t.

If the function returns true it does nothing, if it returns false, it outputs the error message and increments the value of $error by 1.

Now what’s that really do?


/[^a-zA-Z0-9\.\-\Ä\ä\Ö\ö\Ü\ü\ ]+$/

The slashes “/” and “/” are delimiters, “^” marks the start of string or line and the Dollar sign “$” the end of the string, or line. The plus-symbol “+” means required.

Knowing what the special characters mean, it actually says the following: A string, from start to finish, may contain this characters (a to z (lower case), A to Z (upper case), the numbers from 0 to 9, a dot (”.”), a hiven (”-”) and the special characters ä, ö ü (both upper and lower case) and space (” “)), and these characters only.

preg_match() is a case sensitiv function, which means it treats “a” and “A” differently. I included upper (”A-Z”) and lower case (”a-z”). So called “special characters” (Special, because they have another meaning in PHP as well. But that’s another story.) have to be escaped, which means you write a backslash in front of it. For example: \- (the hiven) or \. (the dot). Other special characters are: “^[$()|*+?{\”.

The other two functions are self explanatory, as they check only for numbers, and numbers and space (”\ “).

I hope you have learned the basics of server side scripting. Feel free to use the above code on your web site. If you need any more help, post a message in our discussion area.

Jan 20 PHP Form Validation - Part II Posted at 9:57 pm | No Comments »

In this tutorial, we will show you how to validate an email address using PHP. PHP is a server-side technology, which is not dependant on the user like client-side validation is.

First, let’s begin with a very simple form where we ask the visitor to supply an email address. A real world example could be a form used to subscribe or unsubsribe from your newsletter and since newsletters are delivered to an email address we would not want to collect anything but a valid email address.

The only real disadvantage to the method I am about to describe is that we will not verify if the email address itself is valid and if it really exists but we will check its formatting, which works well in over 90% of all cases.

To check if an email address really exists, there are ways to query the mailserver - though those do not work in many cases because it also opens the door for spammers - or the more popular method called “double-opt-in”, which involves sending an email to the subscriber with a mandatory action - for example, to click a link, or a reply - to confirm subscription or unsubscription from a service. Confirming a subscription is part of the CANSPAM act.

For purposes of this tutorial, newsletters and CANSPAM are not the objective, so let’s get started with the form.

<html>
<head></head>
<body>
<form action="handler.php" method="post">
<label for="the_email_id">Email</label>:<br />
<input type="text" name="the_email"
id="the_email_id" size="20" maxlength="60" /><br />
<input type="submit" name="submit_btn"
value="check email address" />
</form>
</body>
</html>

The form is fairly self-explanatory, a single text field and a submit button. The script to handle the validation process will be named “handler.php”, as the form’s “action” suggests.

Here is the script:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET')
{
  die('No post.');
}
$email = (string) $_POST['the_email'];
if (empty($email))
{
  die('You did not enter anything. Please go
<a href="javascript:history.back(-1);">back</a>.');
}
if (!eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+
(.[a-z0-9-]+)*(.[a-z]{2,4})$", $email))
{
  die('Your email address does not follow the
basic format. Sorry, please try again!');
}
echo sprintf('Your email address "%s"
looks valid. Thank you!', $email);

/*
  continue here with further processing, for example
subscribe/unsubscribe process
*/
?>

Now let’s walk through this piece of code step by step.

At first, we verify that the form was submitted via “post” (remember the HTML?). Why is this important? Well, we do not want people to tinker with our code. Tinkering leads to exploiting, and since we expect the email address to be in PHP’s $_POST (which also hints on a required “post” method), this is a good way to start.

If we pass the “post”-check, we continue to check if anything was entered at all. This is not a necessary step as the following step will catch this as well, but a check performed on empty() is also a lot faster than a regular expression. Doing this gives us the possibility to exit early and actually save resources.

(On a sidenote: This is also a preferred measure when you deal with databases and maybe more critical data on other levels. You always want to verify what you got and if you got anything at all and prevent malicous code from entering further layers of your application.)

Last but not least we use a regular expression to test the format of the string/email supplied by the user.

"^[_a-z0-9-]+(.[_a-z0-9-]+)
*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$"

A more closer look reveals that we allow characters from a to z, 0 to 9, a underscore, hyphen, and a dot to come in front of the “@”-symbol. Following the “@” we basically allow the same, but force an extension in the end. And the extension on email addresses are supposed to be characters only, with a minimum length of two characters and maxmimum length of (currently) four.

Using this full method, we have email validation up and running in virtually no time. The code is small and could be wrapped into a function - which for example returns true or false testing the email address - to refactor the code and could therefore be used inside your existing projects.

KickApps
Clicky Web Analytics

community discussion