Skip to content

Instantly share code, notes, and snippets.

@Deathnerd
Created November 11, 2015 20:52
Show Gist options
  • Select an option

  • Save Deathnerd/0a3b79b28f4e2a97f1d1 to your computer and use it in GitHub Desktop.

Select an option

Save Deathnerd/0a3b79b28f4e2a97f1d1 to your computer and use it in GitHub Desktop.
<?
// Old Code
function CheckCC($field, $msg)
{
$Name = 'n/a';
$Num = $this->_getValue($field);
// Innocent until proven guilty
$GoodCard = true;
// Get rid of any non-digits
$Num = preg_replace("/[^[:digit:]]/", "", $Num);
// Perform card-specific checks, if applicable
switch ($Name)
{
case "mcd" :
$GoodCard = ereg("^5[1-5].{14}$", $Num);
break;
case "vis" :
$GoodCard = ereg("^4.{15}$|^4.{12}$", $Num);
break;
case "amx" :
$GoodCard = ereg("^3[47].{13}$", $Num);
break;
case "dsc" :
$GoodCard = ereg("^6011.{12}$", $Num);
break;
case "dnc" :
$GoodCard = ereg("^30[0-5].{11}$|^3[68].{12}$", $Num);
break;
case "jcb" :
$GoodCard = ereg("^3.{15}$|^2131|1800.{11}$", $Num);
break;
}
// The Luhn formula works right to left, so reverse the number.
$Num = strrev($Num);
$Total = 0;
$str_len = strlen($Num);
for ($x=0; $x<$str_len; $x++)
{
$digit = substr($Num,$x,1);
// If it's an odd digit, double it
if ($x/2 != floor($x/2))
{
$digit *= 2;
// If the result is two digits, add them
if (strlen($digit) == 2)
$digit = substr($digit,0,1) + substr($digit,1,1);
}
// Add the current digit, doubled and added if applicable, to the Total
$Total += $digit;
}
// If it passed (or bypassed) the card-specific check and the Total is
// evenly divisible by 10, it's cool!
if ($GoodCard && $Total % 10 == 0)
return true;
else
{
$this->_errorList[] = array("field" => $field, "value" => $Num, "msg" => $msg);
return false;
}
}
// New shiny code
/**
* Check if a Credit Card is valid according to the Luhn Algorithm
* @see https://en.wikipedia.org/wiki/Luhn_algorithm
* @see http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#PHP
* @param $field
* @param $msg
* @return bool
*/
function CheckCC($field, $msg)
{
$num = $this->_getValue($field);
$str = '';
// Double every other digit
foreach (array_reverse(str_split($num)) as $index => $digit){
$str .= $digit * (2 >> ($index % 2));
}
// sum the result. If divisible by 10, then it's good!
if (!array_sum(str_split($str)) % 10 == 0) {
$this->_errorList[] = array("field" => $field, "value" => $num, "msg" => $msg);
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment