PHP Forms Validating Form Input: Credit Cards - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Forms Validating Form Input: Credit Cards - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

PHP Forms

Validating Form Input: Credit Cards

Problem

You want to make sure a user hasn’t entered a bogus credit card number.

Solution

Example  Validating a credit card number

function is_valid_credit_card(\$s) {
// Remove non-digits and reverse
\$s = strrev(preg_replace('/[^\d]/','',\$s));
// compute checksum
\$sum = 0;
for (\$i = 0, \$j = strlen(\$s); \$i < \$j; \$i++) {
// Use even digits as-is
if ((\$i % 2) == 0) {
\$val = \$s[\$i];
} else {
// Double odd digits and subtract 9 if greater than 9
\$val = \$s[\$i] * 2;
if (\$val > 9) { \$val -= 9; }
}
\$sum += \$val;
}
// Number is valid if sum is a multiple of ten
return ((\$sum % 10) == 0);
}

if (! is_valid_credit_card(\$_POST['credit_card'])) {
print 'Sorry, that card number is invalid.';
}

Discussion

Credit cards use the Luhn algorithm to prevent against accidental error. This algorithm, which the is_valid_credit_card() function in uses, does some manipulations on the individual digits of the card number to tell whether the number is acceptable.

Validating a credit card is a bit like validating an email address. Syntactic validation— making sure the provided value is a sequence of characters that matches a standard— is relatively easy. Semantic validation, however, is trickier. The credit card number 4111 1111 1111 1111 sails through the function but isn’t valid. It’s a well-known test number that looks like a Visa card number. (And, as such, is handy for using in books when one needs an example.)

Just as strong email address validation requires external verification (usually by sending a message to the address with a confirmation link in it), credit card validation requires external validation by submitting the credit card number to a payment processor along with associated account info (cardholder name and address) and making sure you get back an approval.

Syntactic validation is good protection against inadvertent user typos but, obviously, is not all you need to do when checking credit card numbers.