# 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

 ` 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.

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

Similar book on Amazon