18
Jun 10

Input Validation

A simple PHP function for INPUT validation.

function check_chars($variable,$what,$min_length, $max_length,$bad_chars){ 
	if (strlen($variable) < $min_length || strlen($variable)  > $max_length) {
		die("$what is not the correct number of chars or is missing.");
	} else if (preg_match("/$bad_chars/i", $variable)) {
		die("Incorrect chars in $what.");
	} else {
		echo "Successful type constraint check for $what.<br \>";
	}
 
	$variable= mysql_real_escape_string($variable); //a good place to escape anything suspicious that might have left.
	return $variable;
}
 
//example usage
 
check_chars($first_name,'First name',2,25,"[^a-z]"); //names should be longer than 2 and less than 25 chars
check_chars($middle_initial,'Middle name',1,1,"[^a-z]"); //we want only the first char from the name
check_chars($address,'Address',2,100,"[^a-z0-9-, ]"); //this could be probably improved
check_chars($city,'City',2,25,"[^s-zA-Z]"); 
check_chars($state,'State',2,2,"[^A-Z]");
check_chars($zip,'Zip',5,5,"[^0-9]");