Here's a few things I use for validation, first and foremost I try to encapsulate as much as I can in a function. Here I've called it check()
<?php
function check($type, $value) {
switch($type) {
case 'unique_id':
//my unique identifiers are all integers and cannot be empty
//Amazon for example would have to make this differently as they
//have more complex identifiers (ASIN)
if(empty($value) || !is_numeric($value) || intval($value) != $value)
return false;
break;
case 'email':
$domain=explode('@', $_POST['email']);
if(!preg_match('/^[\d\w\.]+@[\d\w\.]\.{2,4}$/', $email) || gethostbyname($domain[1]) == $domain[1])
return false;
break;
default: //if we don't understand the type we have to fail it
return false;
}
return true;
}
?>
Now you can add all your validation rules in one place and use them all around your site. Then, when you need to modify one of these rules (and you'll always need to), there is only one place you need to make the change.
Take a look at the code below for some very flexible techniques for validation.
<?php
//Two arrays, one for required fields and one for allowed fields. The allowed fields is by nature going to be a superset of the required fields
//so we can just build the one from the other
$required_fields=array('requiredfield1', 'requiredfield2', 'requiredfield3');
$allowed_fields=array_merge($required_fields, array('notrequiredfield1', 'notrequiredfield2'));
//This array will hold any unknown fields which manage to work their way in (prehapse someone is trying to hack our script!)
$unknown_fields=array();
//Iterate through the whole POST array (or GET array or even COOKIE array) to weed out the unknown fields and unset ones which
//are present but blank
foreach($_POST as $key => $value) {
//Check if it's a known field
if(!in_array($key, $allowed_fields))
$unknown_fields[]="$key [$value]";
//Remove it if it's empty. This may not be something you want to do prehapse it would be better to
//if(in_array($key, $required_fields) && empty($value)) or something else, depends on your system
if(empty($value))
unset($_POST[$key]);
}
//If nothing is wrong they will pass so we initialize this switch to true
$pass=true;
//Determine which required fields are not present
$missing_fields=array_diff($required_fields, array_keys($_POST));
//Check the unknown fields
if(count($unknown_fields)>0) {
echo("The following unknown fields were used: ".implode(',', $unknown_fields)."<br />\n");
$pass=false;
}
//Check the missing fields
if(count($missing_fields)>0) {
echo("The following required fields were missing: ".implode(',', $missing_fields)."<br />\n");
$pass=false;
}
//exit if fail
if(!$pass) exit();
?>
HTH