Article

Creating a Credit Card Validation Class With PHP

Page: 1 2 3 4 5 6 7 Next

A common function when working with credit cards is displaying the details that you've captured from that user back to them as a confirmation. For example, if the user entered a credit card number of 4111111111111111, then you might want to only show part of the number to them, such as 4111111111111xxxx. Our CCreditCard class contains a function called SafeNumber, which accepts two arguments. The first is the character to mask the digits with, and the second is the number of digits to mask (from the right):

function SafeNumber($char = 'x', $numToHide = 4)    
{    
  // Return only part of the number    
  if($numToHide < 4)    
  {    
    $numToHide = 4;    
  }    
   
  if($numToHide > 10)    
  {    
    $numToHide = 10;    
  }    
   
  $cardNumber = $this->__ccNum;    
  $cardNumber = substr($cardNumber, 0, strlen($cardNumber) - $numToHide);    
   
  for($i = 0; $i < $numToHide; $i++)    
  {    
    $cardNumber .= $char;    
  }    
   
  return $cardNumber;    
}

If we had an instance of our CCreditCard class called $cc1 and the credit card number stored in this class was 4242424242424242, then we could mask the last 6 digits like this: echo $cc1->SafeNumber('x', 6).

The last function contained in our CCreditCard class is called IsValid, and implements the Mod 10 algorithm against the credit card number of our class, returning true/false.

It starts of by setting two variables ($validFormat and $passCheck) to false:

function IsValid()    
{    
  // Not valid by default    
  $validFormat = false;    
  $passCheck = false;

Next we make sure that the credit card number is formatted correctly. We use PHP's ereg function to do this. The regular expression that must be matched is different for each card:

// Is the number in the correct format?    
switch($this->__ccType)    
{    
  case CARD_TYPE_MC:    
    $validFormat = ereg("^5[1-5][0-9]{14}$", $this->__ccNum);    
    break;    
case CARD_TYPE_VS:    
    $validFormat = ereg("^4[0-9]{12}([0-9]{3})?$", $this->__ccNum);    
    break;    
case CARD_TYPE_AX:    
    $validFormat = ereg("^3[47][0-9]{13}$", $this->__ccNum);    
    break;    
case CARD_TYPE_DC:    
    $validFormat = ereg("^3(0[0-5]|[68][0-9])[0-9]{11}$", $this->__ccNum);    
    break;    
case CARD_TYPE_DS:    
    $validFormat = ereg("^6011[0-9]{12}$", $this->__ccNum);    
    break;    
case CARD_TYPE_JC:    
    $validFormat = ereg("^(3[0-9]{4}|2131|1800)[0-9]{11}$", $this->__ccNum);    
    break;    
  default:    
  // Should never be executed    
  $validFormat = false;    
}

At this point, $validFormat will be true (ereg returns true/false) if the credit card number is in the correct format, and false if it's not.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links