2.9 Validating Credit Card Numbers


You want to validate a user 's credit card number.

Technique

For simple validation, use the Luhn-10 algorithm:

 <?php $validated = validate_credit_card ($cred_card_num, $cc_type); function validate_credit_card ($cc_num,  $cc_type='no clue') {     $cc_type = strtolower ($cc_type);     $cc_num = ereg_replace ('[-[:space:]]',  '', $cc_num);     switch ($cc_type)     {         case 'mastercard':               if (strlen ($cc_num) != 16                  !ereg ('^5[1-5]', $cc_num)) {                 return false;             }             break;         case 'visa':             if (strlen ($cc_num) != 13 &&                 (strlen ($cc_num)  != 16                   $cc_num[0] != '4')) {                 return false;             }             break;         case 'amex':             if (strlen ($cc_num) != 15                  !ereg ('^3[47]', $cc_num)) {                 return false;             }             break;         case 'discover':             if (strlen ($cc_num) != 16                  substr ($cc_num, 0, 4) != '6011') {                 return false;             }             break;         default:             if ($cc_type != 'no clue') return -1;             break;     }     $digits  =  preg_split("//", $cc_num);     $num_digits = count ($digits);     for  ($i = ($num_digits-2), $j = 0;           $i >= 0;           $i -= 2, $j++) {         $double_digits[$j]  =  $digits[$i]  *  2;     }     $validate=0;     for  ($i = 0; $i < $num_digits; $i++) {         $tmp_add = preg_split("//", $double_digits[$i]);         for  ($j = 0; $j < count ($tmp_add); $j++) {             $validate += $tmp_add[$j];         }         unset($tmp_add);    }    for  ($i = ($number_digits-1);  $i >= 0;  $i -= 2) {        $validate += $digits[$i];    }    if  (substr ($validate,  -1,  1)  ==  '0') { return true; }    else { return false; } } ?> 

Comments

The validate_credit_card() function validates the credit card number based on the Luhn-10 algorithm. However, please note that any experienced hacker can easily spoof this routine, and it is more of a basic check to find user typos than a security system.

If $cc_type is visa , mastercard , discover , or amex , a little more than the normal validation will be done on the credit card. The function returns 1 if valid, if not valid, and -1 if the $cc_type is given but is not any of the aforementioned.

Note

For more sophisticated credit card validation, you can use one of PHP's many payment processing systems which allow you to interface with various Internet services to accept payments in realtime.




PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net