Check A Credit Card Number Passes Luhn Check

When you accept credit card numbers on your website you need to do a number of different validation checks on the credit card numbers the user enters. When the form is submitted you will need to check that the user has filled out the correct credit card number, expiry date and security code number. Before you send this to the bank or payment gateway for them to validate and process you can do a couple of basic checks to make sure your not sending them poor data.

For example you can check if the expiry date is not empty and is in the correct format of mm/yy, you can check that the security code number is 3 digits and check that the credit card number is 16 digits long. But you can also check if the credit card number is a valid number by using the Luhn algorithm. This is an algorithm that credit card companies will use to generate the credit card numbers, so you can use this to see if this number is a valid credit card number. It is not designed to check if the credit card number is a real number, it will simply check that the numbers are in the correct numeric format. It will catch human error inputs of a credit card number.

The below function can be used to check if a credit card passes the Luhn algorithm, if it does you can submit the credit card number to the bank or payment gateway.

/** * Determines whether the supplied PAN is valid. Will also check to see whether the PAN is numeric. * @param pan The PAN to validate. * @return If the PAN failed the Luhn Check of if the PAN is not numeric. */ public function isValidLuhn($pan) {

if (!ctype_digit((string)$pan)) { return false; }

$nSum = 0; for ($nPos = strlen($pan) - 1, $nMultiple = 0; $nPos >= 0; $nPos--, $nMultiple ^= 1) { $nProduct = $pan{$nPos} * ($nMultiple + 1); $nSum += (($nProduct > 9) ? $nProduct - 9 : $nProduct); } return (($nSum % 10) === 0); }

Back to top

Learn how to code with Treehouse

  • Learn projects with access to 1000+ videos
  • Practice live with our Code Challenge Engine
  • Get help in our members-only forums

Start with a 7 day free trial