Plan Zero [OLD SITE]

Please note that this is content from my old website and is no longer maintained; please see the current website for new content

PHP Luhn modulus implementation

The following luhn_check() function is a small PHP function which checks whether a number is a valid based on the Luhn algorithm. One common example of use is with credit and debit card numbers. This function may be used to check for valid credit card numbers, however additional checks may be desired, such as card prefix and length checks.



<?php
/* Luhn algorithm number checker - (c) 2005-2008 - planzero.org            *
 * This code has been released into the public domain, however please      *
 * give credit to the original author where possible.                      */
 
function luhn_check($number) {
 
  // Strip any non-digits (useful for credit card numbers with spaces and hyphens)

  $number=preg_replace('/\D/', '', $number);
 
  // Set the string length and parity

  $number_length=strlen($number);
  $parity=$number_length % 2;

 
  // Loop through each digit and do the maths
  $total=0;
  for ($i=0; $i<$number_length; $i++) {

    $digit=$number[$i];
    // Multiply alternate digits by two
    if ($i % 2 == $parity) {

      $digit*=2;
      // If the sum is two digits, add them together (in effect)
      if ($digit > 9) {

        $digit-=9;
      }
    }
    // Total up the digits
    $total+=$digit;

  }
 
  // If the total mod 10 equals 0, the number is valid
  return ($total % 10 == 0) ? TRUE : FALSE;

 
}
 
?>
This entry was written by Plan Zero , posted on Wednesday August 26 2009at 10:08 pm

Please note that this is content from my old website and is no longer maintained; please see the current website for new content