Credit card validation in php


/ Published in: PHP
Save to your folder(s)

Validate the credit card number is valid or not


Copy this code and paste it in your HTML
  1. <?php
  2. function validateCC($cc_num, $type) {
  3.  
  4. if($type == "American") {
  5. $denum = "American Express";
  6. } elseif($type == "Dinners") {
  7. $denum = "Diner's Club";
  8. } elseif($type == "Discover") {
  9. $denum = "Discover";
  10. } elseif($type == "Master") {
  11. $denum = "Master Card";
  12. } elseif($type == "Visa") {
  13. $denum = "Visa";
  14. }
  15.  
  16. if($type == "American") {
  17. $pattern = "/^([34|37]{2})([0-9]{13})$/";//American Express
  18. if (preg_match($pattern,$cc_num)) {
  19. $verified = true;
  20. } else {
  21. $verified = false;
  22. }
  23.  
  24.  
  25. } elseif($type == "Dinners") {
  26. $pattern = "/^([30|36|38]{2})([0-9]{12})$/";//Diner's Club
  27. if (preg_match($pattern,$cc_num)) {
  28. $verified = true;
  29. } else {
  30. $verified = false;
  31. }
  32.  
  33.  
  34. } elseif($type == "Discover") {
  35. $pattern = "/^([6011]{4})([0-9]{12})$/";//Discover Card
  36. if (preg_match($pattern,$cc_num)) {
  37. $verified = true;
  38. } else {
  39. $verified = false;
  40. }
  41.  
  42.  
  43. } elseif($type == "Master") {
  44. $pattern = "/^([51|52|53|54|55]{2})([0-9]{14})$/";//Mastercard
  45. if (preg_match($pattern,$cc_num)) {
  46. $verified = true;
  47. } else {
  48. $verified = false;
  49. }
  50.  
  51.  
  52. } elseif($type == "Visa") {
  53. $pattern = "/^([4]{1})([0-9]{12,15})$/";//Visa
  54. if (preg_match($pattern,$cc_num)) {
  55. $verified = true;
  56. } else {
  57. $verified = false;
  58. }
  59.  
  60. }
  61.  
  62. if($verified == false) {
  63. //Do something here in case the validation fails
  64. echo "Credit card invalid. Please make sure that you entered a valid <em>" . $denum . "</em> credit card ";
  65.  
  66. } else { //if it will pass...do something
  67. echo "Your <em>" . $denum . "</em> credit card is valid";
  68. }
  69.  
  70.  
  71. }
  72. echo validateCC("4111111111111111", "Visa");
  73. ?>

URL: http://www.roscripts.com/How_to_validate_credit_card_numbers-106.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.