Article

Creating a Credit Card Validation Class With PHP

Page: 1 2 3 4 5 6 7 Next

We can take advantage of PHP's built-in support for regular expressions by using the ereg_replace function to strip out all non-numeric characters from the credit card number:

// Don't check the number yet,    
// just kill all non numerics    
if(!empty($num))    
{    
  $cardNumber = ereg_replace("[^0-9]", "", $num);    
   
  // Make sure the card number isnt empty    
  if(!empty($cardNumber))    
  {    
    $this->__ccNum = $cardNumber;    
  }    
  else    
  {    
    die('Must pass number to constructor');    
  }    
}    
else    
{    
  die('Must pass number to constructor');    
}

We finish off our CCreditCard constructor by making sure that both the expiry month and year are valid, numerical values:

if(!is_numeric($expm) || $expm < 1 || $expm > 12)    
{    
  die('Invalid expiry month of ' . $expm . ' passed to constructor');    
}    
else    
{    
  $this->__ccExpM = $expm;    
}    
   
// Get the current year    
$currentYear = date('Y');    
settype($currentYear, 'integer');    
   
if(!is_numeric($expy) || $expy < $currentYear || $expy    
> $currentYear + 10)    
{    
  die('Invalid expiry year of ' . $expy . ' passed to constructor');    
}    
else    
{    
  $this->__ccExpY = $expy;    
}    
}

In our CCreditCard class, the only way to set the values of the credit card's details is through the constructor. To retrieve the values of our class-specific variables ($__ccName, $__ccType, etc), we create several functions, like this:

function Name()    
{    
  return $this->__ccName;    
}    
   
function Type()    
{    
  switch($this->__ccType)    
    {    
    case CARD_TYPE_MC:    
      return 'mastercard [1]';    
      break;    
    case CARD_TYPE_VS:    
      return 'Visa [2]';    
      break;    
    case CARD_TYPE_AX:    
      return 'Amex [3]';    
      break;    
    case CARD_TYPE_DC:    
      return 'Diners Club [4]';    
      break;    
    case CARD_TYPE_DS:    
      return 'Discover [5]';    
      break;    
    case CARD_TYPE_JC:    
      return 'JCB [6]';    
      break;    
    default:    
      return 'Unknown [-1]';    
  }    
}    
   
function Number()    
{    
  return $this->__ccNum;    
}    
   
function ExpiryMonth()    
{    
  return $this->__ccExpM;    
}    
   
function ExpiryYear()    
{    
  return $this->__ccExpY;    
}

These functions allow us to retrieve the values of the variables contained within our class. For example, if I created an instance of our CCreditCard class called $cc1, then I could retrieve its expiration month using $cc1->ExpiryMonth().

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

Sponsored Links