PHP Luhn Checker - validates credit cards etc


2008-06-09 Digg! icurtain Delcious icurtain Technorati icurtain


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

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