Location: PHPKode > scripts > EZ Framework > ez-framework/form_handle.php
<?php
# Version 1.02

class form_handle
{
	var $error_msg;
	var $error_blob;
	var $pass = true;
	var $result_var;
	var $method = NULL;
	var $method_name = NULL;
	var $js = '';
	var $use_js = false;

	##-----------------------------------------------------------------------------##
	##                     	Activate Javascript Validation                         ##
	##-----------------------------------------------------------------------------##
	function useJS()
	{
		$this->use_js = true;
	}
	##------------------------------------------------------------------------------##
	##                  Echo Out JavaScript Validation In Header                    ##
	##------------------------------------------------------------------------------##
	function displayJS()
	{
		if($this->use_js && !empty($this->js))
		{
			echo '<script language="javascript" type="text/javascript">';
			echo "function validateForm(form){";
			echo $this->js;
			echo "}";
			echo "</script>";
		}
	}
	##------------------------------------------------------------------------------##
	##                          Allow POST && || GET Method                         ##
	##------------------------------------------------------------------------------##
	function allowMethod( $methods = '' )
	{
		$methods = explode( ',', $methods );
		if( is_array( $methods ) ) 
		{
			$used_method = $_SERVER['REQUEST_METHOD'];
			if( in_array( $used_method, $methods ) )
			{
				if( $used_method == 'POST' )
				{
					$this->method = $_POST;
					$this->method_name = 'POST';
				} else
				{
					$this->method = $_GET;
					$this->method_name = 'GET';
				}
				return true;
			} else
				return false;
		} else
			return false;
	}

	//Get the key name of an array element
	function KeyName( $myArray, $pos )
	{
		if ( ($pos < 0) || ( $pos >= count($myArray) ) )
			return "NULL";
		reset( $myArray );
		for( $i = 0;$i < $pos; $i++ )
			next( $myArray );
		return key( $myArray );
	}
	##------------------------------------------------------------------------------##
	##                 Verify Submit Method Vs Accepted Method(s)                   ##
	##------------------------------------------------------------------------------##
	function testMethod( $msg = 'Error: Request Method Not Accepted' )
	{
		if( $this->method_name == 'POST' && $_SERVER['REQUEST_METHOD'] == 'POST' )
			return true;
		if( $this->method_name == 'GET' && $_SERVER['REQUEST_METHOD'] == 'GET' )
			return true;
		$this->error_msg[$ref] = $msg;
		$this->pass = false;
		return false;	
	}

	##------------------------------------------------------------------------------##
	##                           Main Form Validation Caller                        ##
	##------------------------------------------------------------------------------##
	function validate( $input = '' )
	{
		if( is_array( $input ) )
		{
			foreach( $input as $key => $row )
			{
				$action = strtoupper( $row[0] );
				switch( $action )
				{
					case 'LENMIN' :
					case 'LENGTHMIN' : 
						// ( reference, value, min, $name, min error message )
						form_handle::valLenMin($row[1], $this->method[$row[2]], $row[3], $row[2], $row[4] );
					break;
					case 'LENMAX' :
					case 'LENGTHMAX' : 
						// ( reference, value, max, name,  max error message )
						form_handle::valLenMax($row[1], $this->method[$row[2]], $row[3], $row[2], $row[4] );
					break;
					case 'REQ' :
					case 'REQUIRED' : 
						// ( reference, value, name, error message )
						form_handle::valRequire($row[1], $this->method[$row[2]], $row[2], $row[3] );
					break;
					case 'DUP1' :
					case 'DUPLICATE_BAD' : 
						// ( reference, query, direction, error message )
						form_handle::valFind($row[1], $row[2], 0, $row[3] );
					break;
					case 'DUP2' :
					case 'DUPLICATE_GOOD' : 
						// ( reference, query, direction, error message )
						form_handle::valFind($row[1], $row[2], 1, $row[3] );
					break;
					case 'EQ' :
					case 'EQUAL' : 
						// ( reference, value1, value2, $name1, $name2, error message )
						form_handle::valEqual($row[1], $this->method[$row[2]], $this->method[$row[3]], $row[2], $row[3], $row[4] );
					break;
					case 'IS' :
					case 'TYPE' : 
						// ( is what, reference, value, name, error message )
						form_handle::valIs($row[1], $row[2], $this->method[$row[3]], $row[3], $row[4] );
					break;
					case 'R' 	:
					case 'REGX' : 
						// ( expression, reference, value, error message )
						form_handle::valRegex($row[1], $row[2], $this->method[$row[3]], $row[3], $row[4] );
					break;
					case 'RI' :
					case 'REGXI' : 
						// ( expression, reference, value, error message )
						form_handle::valRegexi($row[1],$row[2], $this->method[$row[3]], $row[3], $row[4] );
					break;
					case 'CC' :
					case 'CREDITCARD' :
						// (  reference, number, card type, error message )
						form_handle::checkCreditCard($row[1], $this->method[$row[2]], $this->method[$row[3]],'','', $row[4] );
					break;
					
					default :
						$this->error_msg['validate_error'] = 'Validation Error: Validation specified not found within class.';
					break;
				}
			}
		}
	}
	##------------------------------------------------------------------------------##
	##                       Clean All Submitted Variables                          ##
	##------------------------------------------------------------------------------##
	function stripAll( )
	{
		if( !( form_handle :: testMethod( ) ) ) return false;
		$x=0;
		//Run cleaning code on each array element
		foreach($this->method as $name)
		{
			if( !is_array( $name ) )
			{
				$key = form_handle::KeyName( $this->method, $x );
				$this->method[$key] = get_magic_quotes_gpc() ? stripslashes( $name ) : $name;
				$this->method[$key] = trim( mysql_escape_string( $this->method[$key] ) );
				$this->method[$key] = htmlspecialchars( $this->method[$key], ENT_QUOTES );
				$this->method[$key] = strip_tags( $this->method[$key], '' );
			}
			$x++;
		}
	}
	##------------------------------------------------------------------------------##
	##                         Clear POST, GET & REQUEST                            ##
	##------------------------------------------------------------------------------##
	// Clear out sent variables so if you want to show the form again after submission but
	// blank again it wont redisplay all the old values
	function clear()
	{
		unset( $_POST );
		unset( $_GET );
		unset( $_REQUEST );
	}
	##------------------------------------------------------------------------------##
	##                  Clean Individual Submitted Variable                         ##
	##------------------------------------------------------------------------------##
	//Clean code on a passed value and return the "claned value"
	//EX: $_POST['name'] = $f->strip($_POST['name']);
	function strip( $name = '' )
	{
		if( !( form_handle :: testMethod( ) ) ) return false;
		$key = form_handle::KeyName( $this->method, $x );
		$this->method[$key] = get_magic_quotes_gpc() ? stripslashes( $name ) : $name;
		$this->method[$key] = trim( mysql_escape_string( $this->method[$key] ) );
		$this->method[$key] = htmlspecialchars( $this->method[$key], ENT_QUOTES );
		$this->method[$key] = strip_tags( $this->method[$key], '' );
		
	}
	##------------------------------------------------------------------------------##
	##                         Force Fail Validation                                ##
	##------------------------------------------------------------------------------##
	//If custom validation outside of class fails then you can force the class validation
	//to also fail
	function forceFail( $ref = 'custom_fail',$msg = 'Failed custom validation' )
	{	
		$this->error_msg[$ref] = $msg;
		$this->pass = false;
	}
	##------------------------------------------------------------------------------##
	##                          Force Pass Validation                               ##
	##------------------------------------------------------------------------------##
	//If for some reason you want to pass on validation even if a part of validation failed
	//in the class this use this
	function forcePass()
	{
		$this->pass = true;
	}
	##------------------------------------------------------------------------------##
	##                   Check TO See If Validation Passed Or Not                   ##
	##------------------------------------------------------------------------------##
	//Calling this function will return a true if all the validations passed
	//Returns false if at least 1 validation failed
	function pass()
	{
		if($this->pass)
			return true;
		else
			return false;
	}
	##-----------------------------------------------------------------------------##
	##                           Query On Validation Pass                          ##
	##-----------------------------------------------------------------------------##
	//if use passed validation execute sent in query
	function queryOnPass( $query )
	{
		if( $this->pass )
		{
			global $sql;
			if( $sql->go( $query ) )
				return true;
			else
				$this->error_msg['Form_Query_Error'] = mysql_error();
			return false;
		}
			return false;
	}

	##-----------------------------------------------------------------------------##
	##                  Validation: Duplication DB Entry                           ##
	##-----------------------------------------------------------------------------##
	// Checks to see if a value is already in the database
	// If you want to error if record found reverse should be 0
	// If you want to error if record was not found set reverse to 1
	function valFind( $ref = '', $query = '', $reverse = 0, $msg = "Value Already In Database" )
	{
		if( !( form_handle :: testMethod( ) ) ) return false;
		global $sql;
		$sql->go($query);
		// Error if record found
		if($reverse == 0)
		{
			if(!$sql->numRows())
				return true;
		}
		// Error if record not found
		else
		{
			if($sql->numRows())
				return true;
		}
		$this->error_msg[$ref] = $msg;
		$this->pass = false;
	}
	##-----------------------------------------------------------------------------##
	##                           Validation: Equal                                 ##
	##-----------------------------------------------------------------------------##
	//Checks to see if two feild are equal
	function valEqual( $ref = '', $name1 = 0, $name2 = 1, $f_name1 = '', $f_name2 = '', $msg = "Fields Did Not Match" )
	{
		if($this->use_js && $f_name1 && $f_name2) $this->js .= "if(form.{$f_name1}.value != form.{$f_name2}.value){form.{$f_name1}.focus();alert(\"{$msg}\"); return false; }";
		if( ( form_handle :: testMethod( ) ) )
		{
			if ($name1 == $name2)
				return true;
	
			$this->error_msg[$ref] = $msg;
			$this->pass = false;
		}
	}
	##-----------------------------------------------------------------------------##
	##                           Validation: Type / Is                             ##
	##-----------------------------------------------------------------------------##
	//Checks to se eif the datatype is->
	function jsIs( $re, $name, $msg)
	{
		if($this->use_js && $name)
			$this->js .= "re = /{$re}/; if(!re.test(form.{$name}.value)){form.{$name}.focus();alert(\"{$msg}\"); return false; }";			
	}
	
	function valIs( $is_what = '', $ref = '', $name = '', $f_name = '', $msg = "Invalid Field" )
	{
		switch( $is_what )
		{
			case 'email':
				$re = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";
				form_handle::jsIs( $re, $f_name, $msg );
				if( eregi( $re, $name ) )return true; break;
			case 'phone':
				$re = "^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))[2-9]\d{2}[- ]?\d{4}$";
				form_handle::jsIs( $re, $f_name, $msg );
				if( eregi( $re, $name ) ) return true; break;
			case 'zip':
				$re = "^((\d{5}-\d{4})|(\d{5})|([AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]\d[A-Za-z]\s?\d[A-Za-z]\d))$";
				form_handle::jsIs( $re, $f_name, $msg );
				if( eregi( $re, $name ) ) return true; break;
			// MM/dd/yyyy with 100% leap years. Valid since year 1900. MM and DD could have 
			// 1 or 2 digits : M/d/yyyy or MM/d/yyyy or M/dd/yyyy
			case 'date':
				$re = "^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$";
				form_handle::jsIs( $re, $f_name, $msg );
				if( eregi( $re, $name ) ) return true; break;
			case 'int':
				$re = "^[0-9]+$";
				form_handle::jsIs( $re, $f_name, $msg );
				if( is_int( $name ) ) return true; break;
			case 'numeric':
				$re = "^[0-9\.]+$";
				form_handle::jsIs( $re, $f_name, $msg );
				if( is_numeric( $name ) ) return true; break;
			case 'float':
				$re = "^[0-9\.]+$";
				form_handle::jsIs( $re, $f_name, $msg );
				if( is_float( $name ) ) return true; break;
			case 'bool':
				if( is_bool( $name ) ) return true; break;
			case 'alphaint':
				$re = "^[a-zA-Z0-9]+$";
				form_handle::jsIs( $re, $f_name, $msg );
				if( eregi( $re, $name ) ) return true; break;
			case 'alphanumeric':
				$re = "^[a-zA-Z0-9\.]+$";
				form_handle::jsIs( $re, $f_name, $msg );
				if( eregi( $re, $name ) ) return true; break;
			case 'alpha':
				$re = "^[a-zA-Z]+$";
				form_handle::jsIs( $re, $f_name, $msg );
				if( eregi( $re, $name ) ) return true; break;
			case 'alphaint_':
				$re = "^[a-zA-Z0-9_]+$";
				form_handle::jsIs( $re, $f_name, $msg );
				if( eregi( $re, $name ) ) return true; break;
			case 'alphanumeric_':
				$re = "^[a-zA-Z0-9\._]+$";
				form_handle::jsIs( $re, $f_name, $msg );
				if( eregi( $re, $name ) ) return true; break;
			case 'alpha_':
				$re = "^[a-zA-Z_]+$";
				form_handle::jsIs( $re, $f_name, $msg );
				if( eregi( $re, $name ) ) return true; break;
			case 'alphaint_s':
				$re = "^[a-zA-Z0-9_ ]+$";
				form_handle::jsIs( $re, $f_name, $msg );
				if( eregi( $re, $name ) ) return true; break;
			case 'alphanumeric_s':
				$re = "^[a-zA-Z0-9\._ ]+$";
				form_handle::jsIs( $re, $f_name, $msg );
				if( eregi( $re, $name ) ) return true; break;
			case 'alpha_s':
				$re = "^[a-zA-Z_ ]+$";
				form_handle::jsIs( $re, $f_name, $msg );
				if( eregi( $re, $name ) ) return true; break;
		}
		if( ( form_handle :: testMethod( ) ) )
		{
			$this->error_msg[$ref] = $msg;
			$this->pass = false;
		}
	}
	##-----------------------------------------------------------------------------##
	##                           Validation: Regexi                                ##
	##-----------------------------------------------------------------------------##
	//Checks data against a custom regular expression (case insensitive)
	function valRegexi( $expression = '', $ref = '', $name = '', $f_name = '^[.]+$', $msg = "Invalid Field" )
	{
		form_handle::jsIs( $expression, $f_name, $msg );
		if ( eregi( $expression, $name ) )
			return true;

		$this->error_msg[$ref] = $msg;
		$this->pass = false;
	}
	##-----------------------------------------------------------------------------##
	##                           Validation: Regex                                 ##
	##-----------------------------------------------------------------------------##
	//Checks data against a custom regular expression (case sensitive)
	function valRegex( $expression = '', $ref = '', $name = '', $f_name = '^[.]+$', $msg = "Invalid Field" )
	{
		form_handle::jsIs( $expression, $f_name, $msg );
		if ( ereg( $expression, $name ) )
			return true;

		$this->error_msg[$ref] = $msg;
		$this->pass = false;
	}
	##-----------------------------------------------------------------------------##
	##                     		Validation: Min Length                             ##
	##-----------------------------------------------------------------------------##
	//Checks data against a min and max character length
	function valLenMin( $ref = '', $name = '', $min = 0, $f_name = '', $msg = "Min Character Length Not Met" )
	{
		if($this->use_js && !empty( $this->method[$f_name] ) ) $this->js .= "if(form.{$f_name}.value.length < {$min}){form.{$f_name}.focus();alert(\"{$msg}\"); return false; }";
		if( ( form_handle :: testMethod( ) ) )
		{
			if( $name != '' )
			{

				if( strlen( trim( $name ) ) < $min )
				{
					$this->error_msg[$ref] = $msg;
					$this->pass = false;
				}
			}
		}
	}
	##-----------------------------------------------------------------------------##
	##                     		Validation: Max Length                             ##
	##-----------------------------------------------------------------------------##
	//Checks data against a min and max character length
	function valLenMax( $ref = '', $name = '', $max = 0, $f_name = '', $msg = "Max Character Length Exceeded" )
	{
		if($this->use_js && !empty( $this->method[$f_name] ) ) $this->js .= "if(form.{$f_name}.value.length > {$max}){form.{$f_name}.focus();alert(\"{$msg}\"); return false; }";
		if( $max != 0 )
		{
			if( strlen( trim( $name ) ) > $max )
			{
				$this->error_msg[$ref] = $msg;
				$this->pass = false;
			}
		}
	}
	##-----------------------------------------------------------------------------##
	##                           Validation: Required                              ##
	##-----------------------------------------------------------------------------##
	//Checks to see if a field was filled in/checked/selected
	function valRequire( $ref = '', $name = '', $f_name = '', $msg = "Field Required" )
	{
		if($this->use_js && $f_name) $this->js .= "if(form.{$f_name}.value == \"\"){form.{$f_name}.focus();alert(\"{$msg}\"); return false; }";
		if( ( form_handle :: testMethod( ) ) )
		{
			if( isset( $name ) && strlen( trim( $name ) ) > 0 )
				return true;
			$this->error_msg[$ref] = $msg;
			$this->pass = false;
		}
	}
	##-----------------------------------------------------------------------------##
	##                                                                             ##
	##++++++++++++++++++++++++++  Display Form Fields  ++++++++++++++++++++++++++++##
	##                                                                             ##
	##-----------------------------------------------------------------------------##
	//This re-display previously submitted form information
	
	##------------------------------------------------------------------------------##
	##                            Set Default Fields                                ##
	##------------------------------------------------------------------------------##
	# Send in the array with the information in it to use for default form values
	# Default database values will be overwritten if POST or GET values are set with the same name
	function setResultVar( $var = '')
	{
		$this->result_var = $var;
	}
	##------------------------------------------------------------------------------##
	##                              Set Text Field                                  ##
	##------------------------------------------------------------------------------##
	# Text
	function setText( $name = '', $default = '' )
	{	
		if( isset( $this->result_var[$name] ) && !( isset( $this->method[$name] ) ) )
			$value = 'value="'.$this->result_var[$name].'"';
		elseif( isset( $this->method[$name] ) )
			$value = isset($this->method[$name]) ? 'value="'.$this->method[$name].'"' : '';
		elseif( !empty( $default ) )
			$value = "value = \"{$default}\"";
		else
			$value = '';
		$name = "name = \"{$name}\"";
		return "{$name} {$value}";
	}
	##------------------------------------------------------------------------------##
	##                                 Set CheckBox                                 ##
	##------------------------------------------------------------------------------##
	# Checkbox
	function setCheckBox( $name = '' )
	{
		if( ! ( isset($this->result_var[$name] ) ) && !( isset( $this->method[$name] ) ) )
			$value = 'checked';
		else
			$value = isset($this->method[$name]) ? 'checked' : '';
		$name = "name=\"{$name}\"";
		return "{$name} {$value}";
	}
	##------------------------------------------------------------------------------##
	##                              Set Radio Button                                ##
	##------------------------------------------------------------------------------##
	# Radio Button
	function setRadio( $name = '', $val = '', $default_val = 0 )
	{
		if( isset( $this->result_var[$name] ) && $this->result_var[$name] == $val && !( isset( $this->method[$name] ) ) )
			$value = "value=\"".$this->result_var[$name]."\" checked=\"checked\"";
		elseif( isset( $this->method[$name] ) && $this->method[$name] == $val )
			$value = "value=\"{$val}\" checked=\"checked\"";
		elseif( !( isset( $this->method[$name] ) ) && $default_val == 1 )
			$value = "value=\"{$val}\" checked=\"checked\"";
		else
			$value = "value=\"{$val}\"";
		$name = "name=\"{$name}\"";
		return "{$name} {$value}";
	}
	##------------------------------------------------------------------------------##
	##                              Set Text Area                                   ##
	##------------------------------------------------------------------------------##
	# TextArea
	function setTextArea( $name = '' )
	{
		if( isset( $this->result_var[$name] ) && ! ( $this->method[$name] ) )
			return $this->result_var[$name];
		else
			return isset($this->method[$name]) ? $this->method[$name] : '';
	}
	##------------------------------------------------------------------------------##
	##                      Set List/Menu + Multiple Selection                      ##
	##------------------------------------------------------------------------------##
	# List/Menu
	function setList( $name = '', $val = '', $default_val = '', $multi = 0 )
	{
		if( $multi == 0 ) //Handle List With No Multiple Selections
		{
			 if( isset($this->result_var[$name]) && $this->result_var[$name] == $val && ! ( isset( $this->method[$name] ) ) )
				$value = "value=\"".$this->result_var[$name]."\" selected";
			elseif( isset( $this->method[$name] ) && $this->method[$name] == $val )
				$value = "value=\"$val\" selected=\"selected\"";
			elseif( !( isset( $this->method[$name] ) ) && $default_val == 1 )
				$value = "value=\"{$val}\" selected=\"selected\"";
			else
				$value = "value=\"{$val}\"";
		} else //Handle List With Multiple Selections
		{
			$name = str_replace(array('[',']'),'',$name);
			if( isset( $this->method[$name] ) )
			{
				if( is_array( $this->method[$name] ) )
				{
					foreach( $this->method[$name] as $o )
					{
						if( $o == $val )
						{
							$value = "value=\"{$val}\" selected=\"selected\"";
							break;
						}
						else
							$value = "value=\"{$val}\"";
					}
				}
			}
			elseif( !( isset( $this->method[$name] ) ) && $default_val == 1 )
				$value = "value=\"{$val}\" selected=\"selected\"";
			else
				$value = "value=\"{$val}\"";
		}
		
		return $value;
	}
	##-----------------------------------------------------------------------------##
	##                                                                             ##
	##+++++++++++++++++++++++++  Display Error Messages  ++++++++++++++++++++++++++##
	##                                                                             ##
	##-----------------------------------------------------------------------------##
	
	##------------------------------------------------------------------------------##
	##                          Get Individual Error Message                        ##
	##------------------------------------------------------------------------------##
	//Return error message on reference name
	function getError( $ref = '', $class = 'form_error', $div = 0 )
	{
		if(isset($this->error_msg[$ref]) && $this->error_msg[$ref])
		{
			if( $div == 1 )
				return "<div class=\"$class\">{$this->error_msg[$ref]}</div>";
			else
				return "<span class=\"$class\">{$this->error_msg[$ref]}</span>";
		}
		else
			return '';
	}
	##------------------------------------------------------------------------------##
	##                              Get All Errors                                  ##
	##------------------------------------------------------------------------------##
	// Return ALL/if any errors that were generated during the validation process
	// $seperate 0 = <br /> *also default
	// $seperate 1 = <br /><br />
	// $seperate 2 = <p>$message</p>
	// $seperate 3 = <span class="$style_class">$message</span>
	// $seperate 4 = <div class="$style_class">$message</div>
	function getErrorBlob( $seperate = 0, $style_class = '' )
	{
		$blob = '';
		if( is_array( $this->error_msg ) )
		{
			switch( $seperate )
			{
				case 1:
					foreach( $this->error_msg as $msg )
						$blob .= "{$msg}<br /><br />";
				break;
				case 2:
					foreach( $this->error_msg as $msg )
						$blob .= "<p>{$msg}</p>";
				break;
				case 3:
					foreach( $this->error_msg as $msg )
						$blob .= "<span class=\"{$style_class}\">{$msg}</span>";
				break;
				case 4:
					foreach( $this->error_msg as $msg )
						$blob .= "<div class=\"{$style_class}\">{$msg}</div>";
				break;
				case 0:
				default:
					foreach( $this->error_msg as $msg )
						$blob .= "{$msg}<br />";
				break;
			}
		} else
			$blob = '';
		return $blob;
	}


	##------------------------------------------------------------------------------##
	##                          Credit Card Validation                              ##
	##------------------------------------------------------------------------------##

	
	/*==============================================================================

	This routine checks the credit card number. The following checks are made:
	
	1. A number has been provided
	2. The number is a right length for the card
	3. The number has an appropriate prefix for the card
	4. The number has a valid modulus 10 number check digit if required
	
	If the validation fails an error is reported.
	
	The structure of credit card formats was gleaned from
		http://www.blackmarket-press.net/info/plastic/check_digit.htm 
	where the details of other cards may also be found.
	
	Input parameters:
				cardnumber           number on the card
				cardname             name of card as defined in the card list below
	Output parameters:
				cardnumber           number on the card
				cardname             name of card as defined in the card list below
	
	Author:     John Gardner
	Date:       4th January 2005
	Updated:    26th February 2005  additional credit cards added
	
	   
	if (isset($_GET['submitted'])) {
	  if (checkCreditCard ($_GET['CardNumber'], $_GET['CardType'], $ccerror, $ccerrortext)) {
		$ccerrortext = 'This card has a valid format';
	  }
	}
	
	==============================================================================*/
	
	
	function checkCreditCard ( $ref, $cardnumber, $cardname, $errornumber = '', $errortext = '', $msg )
	{
	
	  // Define the cards we support. You may add additional card types.
	  
	  //  Name:      As in the selection box of the form - must be same as user's
	  //  Length:    List of possible valid lengths of the card number for the card
	  //  prefixes:  List of possible prefixes for the card
	  //  checkdigit Boolean to say whether there is a check digit
	  
	  // Don't forget - all but the last array definition needs a comma separator!
	  
	  $cards = array ( array ('name' => 'Visa', 
							  'length' => '13,16', 
							  'prefixes' => '4',
							  'checkdigit' => true
							 ),
					   array ('name' => 'MasterCard', 
							  'length' => '16', 
							  'prefixes' => '51,52,53,54,55',
							  'checkdigit' => true
							 ),
					   array ('name' => 'DinersClub', 
							  'length' => '14',
							  'prefixes' => '300,301,302,303,304,305,36,38',
							  'checkdigit' => true
							 ),
					   array ('name' => 'CarteBlanche', 
							  'length' => '14', 
							  'prefixes' => '300,301,302,303,304,305,36,38',
							  'checkdigit' => true
							 ),
					   array ('name' => 'AmericanExpress', 
							  'length' => '15', 
							  'prefixes' => '34,37',
							  'checkdigit' => true
							 ),
					   array ('name' => 'Discover', 
							  'length' => '16', 
							  'prefixes' => '6011',
							  'checkdigit' => true
							 ),
					   array ('name' => 'JCB', 
							  'length' => '15,16', 
							  'prefixes' => '3,1800,2131',
							  'checkdigit' => true
							 ),
					   array ('name' => 'Enroute', 
							  'length' => '15', 
							  'prefixes' => '2014,2149',
							  'checkdigit' => true
							 )
					 );        
	
	  $ccErrorNo = 0;
	
	  $ccErrors [0] = "Unknown card type";
	  $ccErrors [1] = "No card number provided";
	  $ccErrors [2] = "Credit card number has invalid format";
	  $ccErrors [3] = "Credit card number is invalid";
	  $ccErrors [4] = "Credit card number is wrong length";
				   
	  // Establish card type
	  $cardType = -1;
	  for ($i=0; $i<sizeof($cards); $i++) {
	
		// See if it is this card (ignoring the case of the string)
		if (strtolower($cardname) == strtolower($cards[$i]['name'])) {
		  $cardType = $i;
		  break;
		}
	  }
	  
	  // If card type not found, report an error
	  if ($cardType == -1) {
		 $errornumber = 0;     
		 $errortext = $ccErrors [$errornumber];
		 $this->error_msg[$ref] = $msg;
		$this->pass = false; 
	  }
	   
	  // Ensure that the user has provided a credit card number
	  if (strlen($cardnumber) == 0)  {
		 $errornumber = 1;     
		 $errortext = $ccErrors [$errornumber];
		 $this->error_msg[$ref] = $msg;
		$this->pass = false; 
	  }
	   
	  // Check that the number is numeric, although we do permit a space to occur  
	  // every four digits. 
	  $cardexp = '^([0-9]{4})[[:space:]]?([0-9]{4})[[:space:]]?([0-9]{4})[[:space:]]?([0-9]{1,4})$';
	  if (!ereg($cardexp,$cardnumber, $matches))  {
		 $errornumber = 2;     
		 $errortext = $ccErrors [$errornumber];
		 $this->error_msg[$ref] = $msg;
		$this->pass = false; 
	  }
	  
	  // Now remove any spaces from the credit card number
	  $cardNo = $matches[1] . $matches[2] . $matches[3] . $matches[4];
		   
	  // Now check the modulus 10 check digit - if required
	  if ($cards[$cardType]['checkdigit']) {
		$checksum = 0;                                  // running checksum total
		$mychar = "";                                   // next char to process
		$j = 1;                                         // takes value of 1 or 2
	  
		// Process each digit one by one starting at the right
		for ($i = strlen($cardNo) - 1; $i >= 0; $i--) {
		
		  // Extract the next digit and multiply by 1 or 2 on alternative digits.      
		  $calc = $cardNo{$i} * $j;
		
		  // If the result is in two digits add 1 to the checksum total
		  if ($calc > 9) {
			$checksum = $checksum + 1;
			$calc = $calc - 10;
		  }
		
		  // Add the units element to the checksum total
		  $checksum = $checksum + $calc;
		
		  // Switch the value of j
		  if ($j ==1) {$j = 2;} else {$j = 1;};
		} 
	  
		// All done - if checksum is divisible by 10, it is a valid modulus 10.
		// If not, report an error.
		if ($checksum % 10 != 0) {
		 $errornumber = 3;     
		 $errortext = $ccErrors [$errornumber];
		 $this->error_msg[$ref] = $msg;
		$this->pass = false;
		}
	  }  
	
	  // The following are the card-specific checks we undertake.
	
	  // Load an array with the valid prefixes for this card
	  $prefix = split(',',$cards[$cardType]['prefixes']);
		  
	  // Now see if any of them match what we have in the card number  
	  $PrefixValid = false; 
	  for ($i=0; $i<sizeof($prefix); $i++) {
		$exp = '^' . $prefix[$i];
		if (ereg($exp,$cardNo)) {
		  $PrefixValid = true;
		  break;
		}
	  }
		  
	  // If it isn't a valid prefix there's no point at looking at the length
	  if (!$PrefixValid) {
		 $errornumber = 3;     
		 $errortext = $ccErrors [$errornumber];
		 $this->error_msg[$ref] = $msg;
		$this->pass = false; 
	  }
		
	  // See if the length is valid for this card
	  $LengthValid = false;
	  $lengths = split(',',$cards[$cardType]['length']);
	  for ($j=0; $j<sizeof($lengths); $j++) {
		if (strlen($cardNo) == $lengths[$j]) {
		  $LengthValid = true;
		  break;
		}
	  }
	  
	  // See if all is OK by seeing if the length was valid. 
	  if (!$LengthValid) {
		 $errornumber = 4;     
		 $errortext = $ccErrors [$errornumber];
		 $this->error_msg[$ref] = $msg;
		$this->pass = false; 
	  };   
	  
	  // The credit card is in the required format.
	  return true;
	}
	/*============================================================================*/

}
?>
Return current item: EZ Framework