Jump to content

Boolean Variables As A Prequisite To Form Action


TSR

Recommended Posts

Complete php newb here. I'm trying to run 3 different form validation scripts - one to validate the basic info fields (check if they're empty etc.) one to verify a credit card number, and the last one is a CAPTCHA. The validation scripts is on the same page as the form and are set to run when the submit button is clicked. The basic format is

 

if validate1(parameters) {
// display errors
} else {
$validate1pass = true;
}

if validate2(parameters) {
// etc...
}

Where $validate1pass is declared at the beginning of my php code as false. The idea was for each function to set it's pass variable to true, so the form action (using post method) would check to see if validate1pass && validate2pass && validate3pass == true and if it is echo the location of my success page.

 

Here's what happens - if there are any errors, everything works great and the page reports the them. However if the form is filled out perfectly, it just reloads. No error messages, and no data in the fields. The variables are apparently now all set to true, since clicking the submit button again, no matter what the form data is goes to my success page witch gets any data entered. Curious, I added an else argument in the form action line to send me to a non-existing page. I tried it again - entered data wrong, got corrected, entered it right and 404. I think the problem is that the button that trigers all my validation functions is the submit button, and it ends up trigering the form action first, which ends up being "".

 

So is this 3 boolean variables approach completely wrong (in which case what would be a good alternative?), or can it be fixed? Would it be possible to make an invisible submit button and have my script trigger that one after the variables are set?

Link to comment
Share on other sites

I kinda hoped to avoid it since the code'sa mess and parts of it being in Serbian don't exactly help, but here it goes.

 

this is the form page

 



<?php
if (!defined('WEB_ROOT')
   || !isset($_GET['step']) || (int)$_GET['step'] != 1) {
exit;
}
$errorMessage = ' ';
?>
<script language="Javascript" type="text/javascript" src="funkcije/kupovina.js"></script>
<script language="Javascript" type="text/javascript" src="funkcije/kartica.js"></script>
<script type="text/javascript">
<!--
function load(){
rowCard.style.display == 'none'; rowBank.style.display == 'none';
} 
//--></script>

<?PHP
$valCCARD = false;
$valCAPTCHA = false;
$valinfo = false;
$formaction = "";

require_once "formvalidator.php";


echo "<b> <center>";
class MyValidator extends CustomValidator
{
function DoValidate(&$formars,&$error_hash)
{

return true;
}
}

if(isset($_POST['btnStep1']))
{
   $validator = new FormValidator();
$validator->addValidation("txtPaymentFirstName","req","Unesite ime narucioca");
$validator->addValidation("txtPaymentLastName","req","Unesite prezima narucioca");
$validator->addValidation("txtPaymentAddress1","req","Unesite adresu narucioca");
$validator->addValidation("txtPaymentPhone","req","Unesite broj telefona narucioca");
$validator->addValidation("txtPaymentState","req","Unesite zemlju narucioca");
$validator->addValidation("txtPaymentCity","req","Unesite grad narucioca");
$validator->addValidation("txtPaymentPostalCode","req","Unesite poštanski broj narucioca");
$validator->addValidation("txtShippingFirstName","req","Unesite ime uplatioca");
$validator->addValidation("txtShippingLastName","req","Unesite prezima uplatioca");
$validator->addValidation("txtShippingAddress1","req","Unesite adresu uplatioca");
$validator->addValidation("txtShippingPhone","req","Unesite broj telefona uplatioca");
$validator->addValidation("txtShippingState","req","Unesite zemlju uplatioca");
$validator->addValidation("txtShippingCity","req","Unesite grad uplatioca");
$validator->addValidation("txtShippingPostalCode","req","Unesite poštanski broj uplatioca");
if(isset($_POST['chkCard'])) {
if (checkCreditCard ($_POST['CardNumber'], $_POST['CardType'], $errornumber, $errortext)) {

$valCCARD = true;

 }else{
     echo "<center>$errortext</center><br>"; // Display ERROR Type/Text
 }
 }
 else {
$valCCARD = true;
}



// Get a key from https://www.google.com/recaptcha/admin/create
$publickey = "6Lc5_NkSAAAAAM2LMamTTpiJWRymRTdp2PWQlLYh";
$privatekey = "6Lc5_NkSAAAAAOjOgMXwVMBXoQEaviNbb5nRpEms";

# the response from reCAPTCHA
$resp = null;
# the error code from reCAPTCHA, if any
$error = null;

# was there a reCAPTCHA response?
if ($_POST["recaptcha_response_field"]) {
       $resp = recaptcha_check_answer ($privatekey,
                                       $_SERVER["REMOTE_ADDR"],
                                       $_POST["recaptcha_challenge_field"],
                                       $_POST["recaptcha_response_field"]);

       if (!$resp->is_valid) {
               echo "Uneli ste pogresan CAPTCHA kod.";
       } else {
$valCAPTCHA = true; 
}
}




   if($validator->ValidateForm())
   {

$valinfo = true;


}
   else
   {



       $error_hash = $validator->GetErrors();
       foreach($error_hash as $inpname => $inp_err)
       {
           echo "<center><p>$inp_err</p></center>\n";
       }        
   }
}

if ($valCCARD && $valCAPTCHA && $valinfo == 1) {
$formaction = "kupovina.php?step=2";
}
echo "</b></center>";
?>








<table width="550" border="0" align="center" cellpadding="10" cellspacing="0">
   <tr> 
       <td>Korak 1 Od 3 : Unesite podatke </td>
   </tr>
</table>
<p id="errorMessage"><?php echo $errorMessage; ?></p>
<form action="<?php echo $formaction;?>" method="post" name="frmCheckout" id="frmCheckout">
   <table width="550" border="0" align="center" cellpadding="5" cellspacing="1" class="entryTable">
       <tr class="entryTableHeader"> 
           <td colspan="2">Podaci o naručiocu</td>
       </tr>
              <tr> 
           <td width="150" class="label">Ime</td>
           <td class="content"><input name="txtPaymentFirstName" type="text" class="box" id="txtPaymentFirstName" size="30" maxlength="50"></td>
       </tr>
       <tr> 
           <td width="150" class="label">Prezime</td>
           <td class="content"><input name="txtPaymentLastName" type="text" class="box" id="txtPaymentLastName" size="30" maxlength="50"></td>
       </tr>
       <tr> 
           <td width="150" class="label">Adresa</td>
           <td class="content"><input name="txtPaymentAddress1" type="text" class="box" id="txtPaymentAddress1" size="50" maxlength="100"></td>
       </tr>
       <tr> 
           <td class="content"><input name="txtPaymentAddress2" type="hidden" class="box" id="txtPaymentAddress2" size="50" maxlength="100"></td>
       </tr>
       <tr> 
           <td width="150" class="label">Tel.</td>
           <td class="content"><input name="txtPaymentPhone" type="text" class="box" id="txtPaymentPhone" size="30" maxlength="32"></td>
       </tr>
       <tr> 
           <td width="150" class="label">Zemlja</td>
           <td class="content"><input name="txtPaymentState" type="text" class="box" id="txtPaymentState" size="30" maxlength="32"></td>
       </tr>
       <tr> 
           <td width="150" class="label">Grad</td>
           <td class="content"><input name="txtPaymentCity" type="text" class="box" id="txtPaymentCity" size="30" maxlength="32"></td>
       </tr>
       <tr> 
           <td width="150" class="label">Poštanski broj</td>
           <td class="content"><input name="txtPaymentPostalCode" type="text" class="box" id="txtPaymentPostalCode" size="10" maxlength="10"></td>
       </tr>
       <tr> 
           <td  class="label">Plaćam kreditnom karticom</td>
<td><input type="checkbox" name="chkCard" id="chkCard" value="checkbox" onclick="CreditForm(this.checked);"> 
 </tr>
       <tr id="rowCard" order="1" style="display:none;"> 
           <td width="150" class="label">Broj Kartice</td>
           <td class="content"><input name="CardNumber" id="CardNumber" type="text"  class="box" size="24" maxlength="24"></td>
       </tr>
       <tr id="rowBank" order="2" style="display:none;"> 
           <td width="150" class="label">Vrsta kreditne kartice</td>
           <td class="content"><select name="CardType" id="CardType"> 
<option value="">--Izaberite--</option>
 <option value="AmEx">American Express</option>
 <option value="MasterCard">MasterCard</option>
 <option value="Visa">Visa</option>

</select>
<img src="slike/kartice.jpg">
</td>



       </tr>
   </table>

   <p> </p>
   <table width="550" border="0" align="center" cellpadding="5" cellspacing="1" class="entryTable">
       <tr class="entryTableHeader"> 
           <td width="150">Podaci o primaocu</td>
           <td><input type="checkbox" name="chkSame" id="chkSame" value="checkbox" onclick="setPaymentInfo(this.checked);"> 
               <label for="chkSame" style="cursor:pointer">Isto kao naručilac</label></td>
       </tr>
       <tr> 
           <td width="150" class="label">Ime</td>
           <td class="content"><input name="txtShippingFirstName" type="text" class="box" id="txtShippingFirstName" size="30" maxlength="50"></td>
       </tr>
       <tr> 
           <td width="150" class="label">Prezime</td>
           <td class="content"><input name="txtShippingLastName" type="text" class="box" id="txtShippingLastName" size="30" maxlength="50"></td>
       </tr>
       <tr> 
           <td width="150" class="label">Adresa</td>
           <td class="content"><input name="txtShippingAddress1" type="text" class="box" id="txtShippingAddress1" size="50" maxlength="100"></td>
       </tr>
       <tr> 
           <td class="content"><input name="txtShippingAddress2" type="hidden" class="box" id="txtShippingAddress2" size="50" maxlength="100"></td>
       </tr>
       <tr> 
           <td width="150" class="label">Tel.</td>
           <td class="content"><input name="txtShippingPhone" type="text" class="box" id="txtShippingPhone" size="30" maxlength="32"></td>
       </tr>
       <tr> 
           <td width="150" class="label">Zemlja</td>
           <td class="content"><input name="txtShippingState" type="text" class="box" id="txtShippingState" size="30" maxlength="32"></td>
       </tr>
       <tr> 
           <td width="150" class="label">Grad</td>
           <td class="content"><input name="txtShippingCity" type="text" class="box" id="txtShippingCity" size="30" maxlength="32"></td>
       </tr>
       <tr> 
           <td width="150" class="label">Poštanski broj</td>
           <td class="content"><input name="txtShippingPostalCode" type="text" class="box" id="txtShippingPostalCode" size="10" maxlength="10"></td>



</table>
   <p align="center"> 

<center>
<?php

//require_once('recaptchalib.php');

$publickey = "6Lc5_NkSAAAAAM2LMamTTpiJWRymRTdp2PWQlLYh"; // you got this from the signup page

echo recaptcha_get_html($publickey);

?>
<input class="box" name="btnStep1" type="submit" id="btnStep1" value="Dalje >>">
</center>
   </p>
</form>

    <p align="center"> 
<img src="slike/ssl.png">
 </p>




Link to comment
Share on other sites

And here is the required formvalidator.php

 

<?PHP
/*
 -------------------------------------------------------------------------
     PHP Form Validator (formvalidator.php)
             Version 1.1
   This program is free software published under the
   terms of the GNU Lesser General Public License.


   This program is distributed in the hope that it will
   be useful - WITHOUT ANY WARRANTY; without even the
   implied warranty of MERCHANTABILITY or FITNESS FOR A
   PARTICULAR PURPOSE.

For updates, please visit:
http://www.html-form-guide.com/php-form/php-form-validation.html

Questions & comments please send to info@html-form-guide.com
 -------------------------------------------------------------------------  
*/


/**
* Carries information about each of the form validations
*/
class ValidatorObj
{
var $variable_name;
var $validator_string;
var $error_string;
}


/**
* Base class for custom validation objects
**/
class CustomValidator 
{
function DoValidate(&$formars,&$error_hash)
{
 return true;
}
}


/** Default error messages*/
define("E_VAL_REQUIRED_VALUE","Please enter the value for %s");
define("E_VAL_MAXLEN_EXCEEDED","Maximum length exceeded for %s.");
define("E_VAL_MINLEN_CHECK_FAILED","Please enter input with length more than %d for %s");
define("E_VAL_ALNUM_CHECK_FAILED","Please provide an alpha-numeric input for %s");
define("E_VAL_ALNUM_S_CHECK_FAILED","Please provide an alpha-numeric input for %s");
define("E_VAL_NUM_CHECK_FAILED","Please provide numeric input for %s");
define("E_VAL_ALPHA_CHECK_FAILED","Please provide alphabetic input for %s");
define("E_VAL_ALPHA_S_CHECK_FAILED","Please provide alphabetic input for %s");
define("E_VAL_EMAIL_CHECK_FAILED","Please provide a valida email address");
define("E_VAL_LESSTHAN_CHECK_FAILED","Enter a value less than %f for %s");
define("E_VAL_GREATERTHAN_CHECK_FAILED","Enter a value greater than %f for %s");
define("E_VAL_REGEXP_CHECK_FAILED","Please provide a valid input for %s");
define("E_VAL_DONTSEL_CHECK_FAILED","Wrong option selected for %s");
define("E_VAL_SELMIN_CHECK_FAILED","Please select minimum %d options for %s");
define("E_VAL_SELONE_CHECK_FAILED","Please select an option for %s");
define("E_VAL_EQELMNT_CHECK_FAILED","Value of %s should be same as that of %s");
define("E_VAL_NEELMNT_CHECK_FAILED","Value of %s should not be same as that of %s");




/**
* FormValidator: The main class that does all the form validations
**/
class FormValidator 
{
var $validator_array;
   var $error_hash;
var $custom_validators;

function FormValidator()
{
 $this->validator_array = array();
       $this->error_hash = array();
 $this->custom_validators=array();
}

function AddCustomValidator(&$customv)
{
 array_push($this->custom_validators,$customv);
}


function addValidation($variable,$validator,$error)
{
 $validator_obj = new ValidatorObj();
 $validator_obj->variable_name = $variable;
 $validator_obj->validator_string = $validator;
 $validator_obj->error_string = $error;
 array_push($this->validator_array,$validator_obj);
}
   function GetErrors()
   {
       return $this->error_hash;
   }


function ValidateForm()
{
 $bret = true;


 $error_string="";
 $error_to_display = "";



 if(strcmp($_SERVER['REQUEST_METHOD'],'POST')==0)
 {
  $form_variables = $_POST;
 }
 else
 {
  $form_variables = $_GET;
 }


       $vcount = count($this->validator_array);



 foreach($this->validator_array as $val_obj)
 {
  if(!$this->ValidateObject($val_obj,$form_variables,$error_string))
  {
   $bret = false;
               $this->error_hash[$val_obj->variable_name] = $error_string;
  }
 }


 if(true == $bret && count($this->custom_validators) > 0)
 {
           foreach( $this->custom_validators as $custom_val)
  {
   if(false == $custom_val->DoValidate($form_variables,$this->error_hash))
   {
 $bret = false;
   }
  }
 }
 return $bret;
}



function ValidateObject($validatorobj,$formvariables,&$error_string)
{
 $bret = true;


 $splitted = explode("=",$validatorobj->validator_string);
 $command = $splitted[0];
 $command_value = '';


 if(isset($splitted[1]) && strlen($splitted[1])>0)
 {
  $command_value = $splitted[1];
 }


 $default_error_message="";

 $input_value ="";


 if(isset($formvariables[$validatorobj->variable_name]))
 {
  $input_value = $formvariables[$validatorobj->variable_name];
 }


 $bret = $this->ValidateCommand($command,$command_value,$input_value,
	 $default_error_message,
	 $validatorobj->variable_name,
	 $formvariables);



 if(false == $bret)
 {
  if(isset($validatorobj->error_string) &&
   strlen($validatorobj->error_string)>0)
  {
   $error_string = $validatorobj->error_string;
  }
  else
  {
   $error_string = $default_error_message;
  }


 }//if
 return $bret;
}

function validate_req($input_value, &$default_error_message,$variable_name)
{
  $bret = true;
      if(!isset($input_value) ||
  strlen($input_value) <=0)
 {
  $bret=false;
  $default_error_message = sprintf(E_VAL_REQUIRED_VALUE,$variable_name);
 }
  return $bret;
}


function validate_maxlen($input_value,$max_len,$variable_name,&$default_error_message)
{
 $bret = true;
 if(isset($input_value) )
 {
  $input_length = strlen($input_value);
  if($input_length > $max_len)
  {
   $bret=false;
   $default_error_message = sprintf(E_VAL_MAXLEN_EXCEEDED,$variable_name);
  }
 }
 return $bret;
}


function validate_minlen($input_value,$min_len,$variable_name,&$default_error_message)
{
 $bret = true;
 if(isset($input_value) )
 {
  $input_length = strlen($input_value);
  if($input_length < $min_len)
  {
   $bret=false;
   $default_error_message = sprintf(E_VAL_MINLEN_CHECK_FAILED,$min_len,$variable_name);
  }
 }
 return $bret;
}


function test_datatype($input_value,$reg_exp)
{
 if(ereg($reg_exp,$input_value))
 {
  return false;
 }
 return true;
}


function validate_email($email) 
{
 return eregi("^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $email);
}


function validate_for_numeric_input($input_value,&$validation_success)
{

 $more_validations=true;
 $validation_success = true;
 if(strlen($input_value)>0)
 {

  if(false == is_numeric($input_value))
  {
   $validation_success = false;
   $more_validations=false;
  }
 }
 else
 {
  $more_validations=false;
 }
 return $more_validations;
}


function validate_lessthan($command_value,$input_value,
               $variable_name,&$default_error_message)
{
 $bret = true;
 if(false == $this->validate_for_numeric_input($input_value,
                                   $bret))
 {
  return $bret;
 }
 if($bret)
 {
  $lessthan = doubleval($command_value);
  $float_inputval = doubleval($input_value);
  if($float_inputval >= $lessthan)
  {
   $default_error_message = sprintf(E_VAL_LESSTHAN_CHECK_FAILED,
	  $lessthan,
	  $variable_name);
   $bret = false;
  }//if
 }
 return $bret ;
}


function validate_greaterthan($command_value,$input_value,$variable_name,&$default_error_message)
{
 $bret = true;
 if(false == $this->validate_for_numeric_input($input_value,$bret))
 {
  return $bret;
 }
 if($bret)
 {
  $greaterthan = doubleval($command_value);
  $float_inputval = doubleval($input_value);
  if($float_inputval <= $greaterthan)
  {
   $default_error_message = sprintf(E_VAL_GREATERTHAN_CHECK_FAILED,
	  $greaterthan,
	  $variable_name);
   $bret = false;
  }//if
 }
 return $bret ;
}


   function validate_select($input_value,$command_value,&$default_error_message,$variable_name)
   {
    $bret=false;
 if(is_array($input_value))
 {
  foreach($input_value as $value)
  {
   if($value == $command_value)
   {
 $bret=true;
 break;
   }
  }
 }
 else
 {
  if($command_value == $input_value)
  {
   $bret=true;
  }
 }
       if(false == $bret)
       {
           $default_error_message = sprintf(E_VAL_SHOULD_SEL_CHECK_FAILED,
                                           $command_value,$variable_name);
       }
    return $bret;
   }


function validate_dontselect($input_value,$command_value,&$default_error_message,$variable_name)
{
   $bret=true;
 if(is_array($input_value))
 {
  foreach($input_value as $value)
  {
   if($value == $command_value)
   {
 $bret=false;
 $default_error_message = sprintf(E_VAL_DONTSEL_CHECK_FAILED,$variable_name);
 break;
   }
  }
 }
 else
 {
  if($command_value == $input_value)
  {
   $bret=false;
   $default_error_message = sprintf(E_VAL_DONTSEL_CHECK_FAILED,$variable_name);
  }
 }
  return $bret;
}




function ValidateCommand($command,$command_value,$input_value,&$default_error_message,$variable_name,$formvariables)
{
 $bret=true;
 switch($command)
 {
  case 'req':
  {
   $bret = $this->validate_req($input_value, $default_error_message,$variable_name);
   break;
  }


  case 'maxlen':
  {
   $max_len = intval($command_value);
   $bret = $this->validate_maxlen($input_value,$max_len,$variable_name,
	    $default_error_message);
   break;
  }


  case 'minlen':
  {
   $min_len = intval($command_value);
   $bret = $this->validate_minlen($input_value,$min_len,$variable_name,
	   $default_error_message);
   break;
  }


  case 'alnum':
  {
   $bret= $this->test_datatype($input_value,"[^A-Za-z0-9]");
   if(false == $bret)
   {
    $default_error_message = sprintf(E_VAL_ALNUM_CHECK_FAILED,$variable_name);
   }
   break;
  }


  case 'alnum_s':
  {
   $bret= $this->test_datatype($input_value,"[^A-Za-z0-9 ]");
   if(false == $bret)
   {
    $default_error_message = sprintf(E_VAL_ALNUM_S_CHECK_FAILED,$variable_name);
   }
   break;
  }


  case 'num':
           case 'numeric':
  {
   $bret= $this->test_datatype($input_value,"[^0-9]");
   if(false == $bret)
   {
    $default_error_message = sprintf(E_VAL_NUM_CHECK_FAILED,$variable_name);
   }
   break;	  
  }


  case 'alpha':
  {
   $bret= $this->test_datatype($input_value,"[^A-Za-z]");
   if(false == $bret)
   {
    $default_error_message = sprintf(E_VAL_ALPHA_CHECK_FAILED,$variable_name);
   }
   break;
  }
  case 'alpha_s':
  {
   $bret= $this->test_datatype($input_value,"[^A-Za-z ]");
   if(false == $bret)
   {
    $default_error_message = sprintf(E_VAL_ALPHA_S_CHECK_FAILED,$variable_name);
   }
   break;
  }
  case 'email':
  {
   if(isset($input_value) && strlen($input_value)>0)
   {
    $bret= $this->validate_email($input_value);
    if(false == $bret)
    {
	 $default_error_message = E_VAL_EMAIL_CHECK_FAILED;
    }
   }
   break;
  }
  case "lt": 
  case "lessthan": 
  {
   $bret = $this->validate_lessthan($command_value,
		 $input_value,
		 $variable_name,
		 $default_error_message);
   break;
  }
  case "gt": 
  case "greaterthan": 
  {
   $bret = $this->validate_greaterthan($command_value,
		 $input_value,
		 $variable_name,
		 $default_error_message);
   break;
  }


  case "regexp":
  {
   if(isset($input_value) && strlen($input_value)>0)
   {
    if(!preg_match("$command_value",$input_value))
    {
	 $bret=false;
	 $default_error_message = sprintf(E_VAL_REGEXP_CHECK_FAILED,$variable_name);
    }
   }
   break;
  }
   case "dontselect": 
   case "dontselectchk":
         case "dontselectradio":
  {
   $bret = $this->validate_dontselect($input_value,
		      $command_value,
		      $default_error_message,
		    $variable_name);
    break;
  }//case


         case "shouldselchk":
         case "selectradio":
                     {
                           $bret = $this->validate_select($input_value,
          $command_value,
          $default_error_message,
	    $variable_name);
                           break;
                     }//case
   case "selmin":
  {
   $min_count = intval($command_value);


   if(isset($input_value))
                           {
       if($min_count > 1)
       {
           $bret = (count($input_value) >= $min_count )?true:false;
       }
                               else
                               {
                                 $bret = true;
                               }
                           }
   else
   {
    $bret= false;
    $default_error_message = sprintf(E_VAL_SELMIN_CHECK_FAILED,$min_count,$variable_name);
   }


   break;
  }//case
  case "selone":
  {
   if(false == isset($input_value)||
    strlen($input_value)<=0)
   {
    $bret= false;
    $default_error_message = sprintf(E_VAL_SELONE_CHECK_FAILED,$variable_name);
   }
   break;
  }
  case "eqelmnt":
  {


   if(isset($formvariables[$command_value]) &&
      strcmp($input_value,$formvariables[$command_value])==0 )
   {
    $bret=true;
   }
   else
   {
    $bret= false;
    $default_error_message = sprintf(E_VAL_EQELMNT_CHECK_FAILED,$variable_name,$command_value);
   }
  break;
  }
   case "neelmnt":
  {
   if(isset($formvariables[$command_value]) &&
      strcmp($input_value,$formvariables[$command_value]) !=0 )
   {
    $bret=true;
   }
   else
   {
    $bret= false;
    $default_error_message = sprintf(E_VAL_NEELMNT_CHECK_FAILED,$variable_name,$command_value);
   }
   break;
  }

 }//switch
 return $bret;
}//validdate command



}

















/************************************************************************************************************
* This function has been placed in the public domain as detailed at:                                       *
* http://www.braemoor.co.uk/software/index.shtml                                                           *
*                                                                                                          *
* "You are welcome to download and use any of this software, but please note that:                         *
* All software is provided as freeware for personal or commercial use without obligation by either party.  *
* The author will not accept responsibility for any problems that may be incurred by use of this software, *
* although any errors reported will be corrected as soon as possible.                                      *
* Re-distribution of this software is NOT permitted without explicit permission."                          *
************************************************************************************************************


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 a variety of sources on 
the web, although the best is probably on Wikepedia ("Credit card number"):


 http://en.wikipedia.org/wiki/Credit_card_number


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        webmister@braemoor.co.uk
Date:       4th January 2005
Updated:    26th February 2005  additional credit cards added
           1st July 2006       multiple definition of Discovery card removed
           27th Nov. 2006      Additional cards added from Wikipedia
           8th Dec 2007      Problem with Solo card definition corrected
           18th Jan 2008      Support for 18 digit Maestro cards added
           26th Nov 2008       Support for 19 digit Maestro cards added
           19th June 2009      Support for Laser debit cards
           11th September 2010 Improved support for Diner Club cards by Noe Leon
           27th October 2011   Minor updates by Neil Cresswell (neil@cresswell.net):
                                 * VISA now only 16 digits as 13 digits version withdrawn and no longer in circulation
                                 * Deprecated eregi replaced by preg_match in two places
                                 * Deprecated split replaced by explode in two places
           10th April 2012     New matches for Maestro, Diners Enroute and Switch
           17th October 2012   Diners Club prefix 38 not encoded

if (isset($_GET['submitted'])) {
 if (checkCreditCard ($_GET['CardNumber'], $_GET['CardType'], $ccerror, $ccerrortext)) {
   $ccerrortext = 'This card has a valid format';
 }
}


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



function checkCreditCard ($cardnumber, $cardname, &$errornumber, &$errortext) {


 // 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' => 'AmEx', 
                         'length' => '15', 
                         'prefixes' => '34,37',
                         'checkdigit' => true
                        ),
                  array ('name' => 'Diners Club Carte Blanche', 
                         'length' => '14', 
                         'prefixes' => '300,301,302,303,304,305',
                         'checkdigit' => true
                        ),
                  array ('name' => 'Diners Club', 
                         'length' => '14,16',
                         'prefixes' => '36,38,54,55',
                         'checkdigit' => true
                        ),
                  array ('name' => 'Discover', 
                         'length' => '16', 
                         'prefixes' => '6011,622,64,65',
                         'checkdigit' => true
                        ),
                  array ('name' => 'Diners Club Enroute', 
                         'length' => '15', 
                         'prefixes' => '2014,2149',
                         'checkdigit' => true
                        ),
                  array ('name' => 'JCB', 
                         'length' => '16', 
                         'prefixes' => '35',
                         'checkdigit' => true
                        ),
                  array ('name' => 'Maestro', 
                         'length' => '12,13,14,15,16,18,19', 
                         'prefixes' => '5018,5020,5038,6304,6759,6761,6762,6763',
                         'checkdigit' => true
                        ),
                  array ('name' => 'MasterCard', 
                         'length' => '16', 
                         'prefixes' => '51,52,53,54,55',
                         'checkdigit' => true
                        ),
                  array ('name' => 'Solo', 
                         'length' => '16,18,19', 
                         'prefixes' => '6334,6767',
                         'checkdigit' => true
                        ),
                  array ('name' => 'Switch', 
                         'length' => '16,18,19', 
                         'prefixes' => '4903,4905,4911,4936,564182,633110,6333,6759',
                         'checkdigit' => true
                        ),
                  array ('name' => 'VISA', 
                         'length' => '16', 
                         'prefixes' => '4',
                         'checkdigit' => true
                        ),
                  array ('name' => 'VISA Electron', 
                         'length' => '16', 
                         'prefixes' => '417500,4917,4913,4508,4844',
                         'checkdigit' => true
                        ),
                  array ('name' => 'LaserCard', 
                         'length' => '16,17,18,19', 
                         'prefixes' => '6304,6706,6771,6709',
                         'checkdigit' => true
                        )
               );


 $ccErrorNo = 0;


 $ccErrors [0] = "Niste odabrali vrstu kartice";
 $ccErrors [1] = "Niste uneli broj kartice";
 $ccErrors [2] = "Broj kartice je nepravilan";
 $ccErrors [3] = "Broj kartice je nevažeci";
 $ccErrors [4] = "Broj kartice je pogrešne dužine";

 // 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];
    return false; 
 }

 // Ensure that the user has provided a credit card number
 if (strlen($cardnumber) == 0)  {
    $errornumber = 1;     
    $errortext = $ccErrors [$errornumber];
    return false; 
 }

 // Remove any spaces from the credit card number
 $cardNo = str_replace (' ', '', $cardnumber);  

 // Check that the number is numeric and of the right sort of length.
 if (!preg_match("/^[0-9]{13,19}$/",$cardNo))  {
    $errornumber = 2;     
    $errortext = $ccErrors [$errornumber];
    return false; 
 }

 // 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];
    return false; 
   }
 }  


 // The following are the card-specific checks we undertake.


 // Load an array with the valid prefixes for this card
 $prefix = explode(',',$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 (preg_match($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];
    return false; 
 }

 // See if the length is valid for this card
 $LengthValid = false;
 $lengths = explode(',',$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];
    return false; 
 };   

 // The credit card is in the required format.
 return true;
}
/*============================================================================*/

















/*
* This is a PHP library that handles calling reCAPTCHA.
*    - Documentation and latest version
*          http://recaptcha.net/plugins/php/
*    - Get a reCAPTCHA API Key
*          https://www.google.com/recaptcha/admin/create
*    - Discussion group
*          http://groups.google.com/group/recaptcha
*
* Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net
* AUTHORS:
*   Mike Crawford
*   Ben Maurer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/


/**
* The reCAPTCHA server URL's
*/
define("RECAPTCHA_API_SERVER", "http://www.google.com/recaptcha/api");
define("RECAPTCHA_API_SECURE_SERVER", "https://www.google.com/recaptcha/api");
define("RECAPTCHA_VERIFY_SERVER", "www.google.com");


/**
* Encodes the given data into a query string format
* @param $data - array of string elements to be encoded
* @return string - encoded request
*/
function _recaptcha_qsencode ($data) {
       $req = "";
       foreach ( $data as $key => $value )
               $req .= $key . '=' . urlencode( stripslashes($value) ) . '&';


       // Cut the last '&'
       $req=substr($req,0,strlen($req)-1);
       return $req;
}




/**
* Submits an HTTP POST to a reCAPTCHA server
* @param string $host
* @param string $path
* @param array $data
* @param int port
* @return array response
*/
function _recaptcha_http_post($host, $path, $data, $port = 80) {


       $req = _recaptcha_qsencode ($data);


       $http_request  = "POST $path HTTP/1.0\r\n";
       $http_request .= "Host: $host\r\n";
       $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
       $http_request .= "Content-Length: " . strlen($req) . "\r\n";
       $http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
       $http_request .= "\r\n";
       $http_request .= $req;


       $response = '';
       if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) {
               die ('Could not open socket');
       }


       fwrite($fs, $http_request);


       while ( !feof($fs) )
               $response .= fgets($fs, 1160); // One TCP-IP packet
       fclose($fs);
       $response = explode("\r\n\r\n", $response, 2);


       return $response;
}




/**
* Gets the challenge HTML (javascript and non-javascript version).
* This is called from the browser, and the resulting reCAPTCHA HTML widget
* is embedded within the HTML form it was called from.
* @param string $pubkey A public key for reCAPTCHA
* @param string $error The error given by reCAPTCHA (optional, default is null)
* @param boolean $use_ssl Should the request be made over ssl? (optional, default is false)


* @return string - The HTML to be embedded in the user's form.
*/
function recaptcha_get_html ($pubkey, $error = null, $use_ssl = true)
{
if ($pubkey == null || $pubkey == '') {
 die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");
}

if ($use_ssl) {
               $server = RECAPTCHA_API_SECURE_SERVER;
       } else {
               $server = RECAPTCHA_API_SERVER;
       }


       $errorpart = "";
       if ($error) {
          $errorpart = "&error=" . $error;
       }
       return '<script type="text/javascript" src="'. $server . '/challenge?k=' . $pubkey . $errorpart . '"></script>


<noscript>
   <iframe src="'. $server . '/noscript?k=' . $pubkey . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/>
   <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
   <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
</noscript>';
}





/**
* A ReCaptchaResponse is returned from recaptcha_check_answer()
*/
class ReCaptchaResponse {
       var $is_valid;
       var $error;
}



/**
 * Calls an HTTP POST function to verify if the user's guess was correct
 * @param string $privkey
 * @param string $remoteip
 * @param string $challenge
 * @param string $response
 * @param array $extra_params an array of extra variables to post to the server
 * @return ReCaptchaResponse
 */
function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array())
{
if ($privkey == null || $privkey == '') {
 die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");
}


if ($remoteip == null || $remoteip == '') {
 die ("For security reasons, you must pass the remote ip to reCAPTCHA");
}




       //discard spam submissions
       if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) {
               $recaptcha_response = new ReCaptchaResponse();
               $recaptcha_response->is_valid = false;
               $recaptcha_response->error = 'incorrect-captcha-sol';
               return $recaptcha_response;
       }


       $response = _recaptcha_http_post (RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify",
                                         array (
                                                'privatekey' => $privkey,
                                                'remoteip' => $remoteip,
                                                'challenge' => $challenge,
                                                'response' => $response
                                                ) + $extra_params
                                         );


       $answers = explode ("\n", $response [1]);
       $recaptcha_response = new ReCaptchaResponse();


       if (trim ($answers [0]) == 'true') {
               $recaptcha_response->is_valid = true;
       }
       else {
               $recaptcha_response->is_valid = false;
               $recaptcha_response->error = $answers [1];
       }
       return $recaptcha_response;


}


/**
* gets a URL where the user can sign up for reCAPTCHA. If your application
* has a configuration page where you enter a key, you should provide a link
* using this function.
* @param string $domain The domain where the page is hosted
* @param string $appname The name of your application
*/
function recaptcha_get_signup_url ($domain = null, $appname = null) {
return "https://www.google.com/recaptcha/admin/create?" .  _recaptcha_qsencode (array ('domains' => $domain, 'app' => $appname));
}


function _recaptcha_aes_pad($val) {
$block_size = 16;
$numpad = $block_size - (strlen ($val) % $block_size);
return str_pad($val, strlen ($val) + $numpad, chr($numpad));
}


/* Mailhide related code */


function _recaptcha_aes_encrypt($val,$ky) {
if (! function_exists ("mcrypt_encrypt")) {
 die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");
}
$mode=MCRYPT_MODE_CBC;   
$enc=MCRYPT_RIJNDAEL_128;
$val=_recaptcha_aes_pad($val);
return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
}



function _recaptcha_mailhide_urlbase64 ($x) {
return strtr(base64_encode ($x), '+/', '-_');
}


/* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
function recaptcha_mailhide_url($pubkey, $privkey, $email) {
if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) {
 die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " .
      "you can do so at <a href='http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>");
}


$ky = pack('H*', $privkey);
$cryptmail = _recaptcha_aes_encrypt ($email, $ky);

return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail);
}


/**
* gets the parts of the email to expose to the user.
* eg, given johndoe@example,com return ["john", "example.com"].
* the email is then displayed as john...@example.com
*/
function _recaptcha_mailhide_email_parts ($email) {
$arr = preg_split("/@/", $email );


if (strlen ($arr[0]) <= 4) {
 $arr[0] = substr ($arr[0], 0, 1);
} else if (strlen ($arr[0]) <= 6) {
 $arr[0] = substr ($arr[0], 0, 3);
} else {
 $arr[0] = substr ($arr[0], 0, 4);
}
return $arr;
}


/**
* Gets html to display an email address given a public an private key.
* to get a key, go to:
*
* http://www.google.com/recaptcha/mailhide/apikey
*/
function recaptcha_mailhide_html($pubkey, $privkey, $email) {
$emailparts = _recaptcha_mailhide_email_parts ($email);
$url = recaptcha_mailhide_url ($pubkey, $privkey, $email);

return htmlentities($emailparts[0]) . "<a href='" . htmlentities ($url) .
 "' onclick=\"window.open('" . htmlentities ($url) . "', '', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300'); return false;\" title=\"Reveal this e-mail address\">...</a>@" . htmlentities ($emailparts [1]);


}















?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.