PHP - Credit card validation class


SUBMITTED BY: efbee

DATE: Oct. 3, 2016, 6:16 p.m.

FORMAT: PHP

SIZE: 2.2 kB

HITS: 625

  1. Credit Card Identification and Validation Class - The credit_card class
  2. provides methods for cleaning, validating and identifying the type of credit card numbers.
  3. <?php
  4. class credit_card
  5. {
  6. function clean_no ($cc_no)
  7. {
  8. // Remove non-numeric characters from $cc_no
  9. return ereg_replace ('[^0-9]+', '', $cc_no);
  10. }
  11. function identify ($cc_no)
  12. {
  13. $cc_no = credit_card::clean_no ($cc_no);
  14. // Get card type based on prefix and length of card number
  15. if (ereg ('^4(.{12}|.{15})$', $cc_no))
  16. return 'Visa';
  17. if (ereg ('^5[1-5].{14}$', $cc_no))
  18. return 'Mastercard';
  19. if (ereg ('^3[47].{13}$', $cc_no))
  20. return 'American Express';
  21. if (ereg ('^3(0[0-5].{11}|[68].{12})$', $cc_no))
  22. return 'Diners Club/Carte Blanche';
  23. if (ereg ('^6011.{12}$', $cc_no))
  24. return 'Discover Card';
  25. if (ereg ('^(3.{15}|(2131|1800).{11})$', $cc_no))
  26. return 'JCB';
  27. if (ereg ('^2(014|149).{11})$', $cc_no))
  28. return 'enRoute';
  29. return 'unknown';
  30. }
  31. function validate ($cc_no)
  32. {
  33. // Reverse and clean the number
  34. $cc_no = strrev (credit_card::clean_no ($cc_no));
  35. // VALIDATION ALGORITHM
  36. // Loop through the number one digit at a time
  37. // Double the value of every second digit (starting from the right)
  38. // Concatenate the new values with the unaffected digits
  39. for ($ndx = 0; $ndx < strlen ($cc_no); ++$ndx)
  40. $digits .= ($ndx % 2) ? $cc_no[$ndx] * 2 : $cc_no[$ndx];
  41. // Add all of the single digits together
  42. for ($ndx = 0; $ndx < strlen ($digits); ++$ndx)
  43. $sum += $digits[$ndx];
  44. // Valid card numbers will be transformed into a multiple of 10
  45. return ($sum % 10) ? FALSE : TRUE;
  46. }
  47. function check ($cc_no)
  48. {
  49. $valid = credit_card::validate ($cc_no);
  50. $type = credit_card::identify ($cc_no);
  51. return array ($valid, $type, 'valid' => $valid, 'type' => $type);
  52. }
  53. }
  54. ?>

comments powered by Disqus