This section of code validates a credit card or any other luhn number - useful as an initial card number check for merchant interfaces etc
the function returns either 0 or 1 depending on whether the luhn check was successful. The luhn check does a load of recursive calculation and then divides by 10 and checks if there is a remainder
- function luhnCheck($number){
-
-
$sum = 0;
-
$alt = false;
-
-
for($i = strlen($number) - 1; $i >= 0; $i--){
-
$n = substr($number, $i, 1);
-
if($alt){
-
//square n
-
$n *= 2;
-
if($n > 9) {
-
//calculate remainder
-
$n = ($n % 10) +1;
-
}
-
}
-
$sum += $n;
-
$alt = !$alt;
-
}
-
//echo $sum;
-
//if $sum divides by 10 with no remainder then it's valid
-
return ($sum % 10 == 0);
-
}