Recipe 9.9. Validating Form Input: Credit Cards

9.9.1. Problem

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

9.9.2. Solution

The is_valid_credit_card( ) function in Example 9-18 tells you whether a provided credit card number is syntactically valid.

Validating a credit card number

<?php 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.'; } ?>

9.9.3. Discussion

Credit cards use the Luhn algorithm to prevent against accidental error. This algorithm, which the is_valid_credit_card( ) function in Example 9-18 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 in Example 9-18 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 (card holder 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.

9.9.4. See Also

Recipe 9.4 for information about validating email addresses; for information about the Luhn algorithm.

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: