[PHP] 验证信用卡卡号代码 Luhn算法 →→→→→进入此内容的聊天室

来自 , 2020-01-13, 写在 PHP, 查看 106 次.
URL http://www.code666.cn/view/3f4366ae
  1. // This function will take a credit card number and check to make sure it
  2. // contains the right amount of digits and uses the Luhn Algorithm to
  3. // weed out made up numbers
  4. function validateCreditcard_number($credit_card_number)
  5. {
  6.     // Get the first digit
  7.     $firstnumber = substr($credit_card_number, 0, 1);
  8.     // Make sure it is the correct amount of digits. Account for dashes being present.
  9.     switch ($firstnumber)
  10.     {
  11.         case 3:
  12.             if (!preg_match('/^3\d{3}[ \-]?\d{6}[ \-]?\d{5}$/', $credit_card_number))
  13.             {
  14.                 return 'This is not a valid American Express card number';
  15.             }
  16.             break;
  17.         case 4:
  18.             if (!preg_match('/^4\d{3}[ \-]?\d{4}[ \-]?\d{4}[ \-]?\d{4}$/', $credit_card_number))
  19.             {
  20.                 return 'This is not a valid Visa card number';
  21.             }
  22.             break;
  23.         case 5:
  24.             if (!preg_match('/^5\d{3}[ \-]?\d{4}[ \-]?\d{4}[ \-]?\d{4}$/', $credit_card_number))
  25.             {
  26.                 return 'This is not a valid MasterCard card number';
  27.             }
  28.             break;
  29.         case 6:
  30.             if (!preg_match('/^6011[ \-]?\d{4}[ \-]?\d{4}[ \-]?\d{4}$/', $credit_card_number))
  31.             {
  32.                 return 'This is not a valid Discover card number';
  33.             }
  34.             break;
  35.         default:
  36.             return 'This is not a valid credit card number';
  37.     }
  38.     // Here's where we use the Luhn Algorithm
  39.     $credit_card_number = str_replace('-', '', $credit_card_number);
  40.     $map = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
  41.                 0, 2, 4, 6, 8, 1, 3, 5, 7, 9);
  42.     $sum = 0;
  43.     $last = strlen($credit_card_number) - 1;
  44.     for ($i = 0; $i <= $last; $i++)
  45.     {
  46.         $sum += $map[$credit_card_number[$last - $i] + ($i & 1) * 10];
  47.     }
  48.     if ($sum % 10 != 0)
  49.     {
  50.         return 'This is not a valid credit card number';
  51.     }
  52.     // If we made it this far the credit card number is in a valid format
  53.     return 'This is a valid credit card number';
  54. }
  55. echo validateCreditcard_number('4111-1111-1111-1111'); // This is a valid credit card number
  56. echo validateCreditcard_number('4111-1111-1111-1112'); // This is not a valid credit card number
  57. echo validateCreditcard_number('5558-545f-1234');      // This is not a valid MasterCard card number
  58. echo validateCreditcard_number('9876-5432-1012-3456'); // This is not a valid credit card number
  59.  
  60.  

回复 "验证信用卡卡号代码 Luhn算法"

这儿你可以回复上面这条便签

captcha