PHP Luhn Checker - validates credit cards etc


2008-06-09


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

input length 16

  1. function luhnCheck($number){
  2. $sum = 0;
  3. $alt = false;
  4. for($i = strlen($number) - 1; $i >= 0; $i--){
  5. $n = substr($number, $i, 1);
  6. if($alt){
  7. //square n
  8. $n *= 2;
  9. if($n > 9) {
  10. //calculate remainder
  11. $n = ($n % 10) +1;
  12. }
  13. }
  14. $sum += $n;
  15. $alt = !$alt;
  16. }
  17. //echo $sum;
  18. //if $sum divides by 10 with no remainder then it's valid
  19. return ($sum % 10 == 0);
  20. }