Given a credit card number and no additional information, what is the best way in PHP to determine whether or not it is a valid number?
Right now I need something that will work with American Express, Discover, MasterCard, and Visa, but it might be helpful if it will also work with other types.
The Luhn algorithm is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers. There is free code available for doing this check in many languages.
Credit card validation codes act as a security measure to help protect your card information and are generally used for transactions when the physical card is not present. This code is used to identify that the person using the card is in fact the account holder and has access to the card physically.
It may mean your account does not allow you to accept payments of this type. These errors are most common with American Express and Discover cards. If not, this error could also indicate an issue with your merchant account. The CV: card type verification error may also occur because of a CVV error.
There are three parts to the validation of the card number:
Most cards use the Luhn algorithm for checksums:
Luhn Algorithm described on Wikipedia
There are links to many implementations on the Wikipedia link, including PHP:
<? /* Luhn algorithm number checker - (c) 2005-2008 shaman - www.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; } ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With