Monday, July 15, 2013

Credit card validation using php


<?php
define("CARD_TYPE_MASTERCARD","CARD_TYPE_MASTERCARD");
define("CARD_TYPE_VISA","CARD_TYPE_VISA");
define("CARD_TYPE_AEX","CARD_TYPE_AEX");
define("CARD_TYPE_DINERS","CARD_TYPE_DINERS");
define("CARD_TYPE_DISCOVER","CARD_TYPE_DISCOVER");
define("CARD_TYPE_JCB","CARD_TYPE_JCB");

function getCardType($cardNumber){
    $cardNumber = preg_replace('/\D/', '', $cardNumber);
    $len = strlen($cardNumber);
    if ($len < 15 || $len > 16) {
        return null;
    } else {
        switch($cardNumber) {
            case(preg_match ('/^4/', $cardNumber) >= 1):
                return CARD_TYPE_VISA;
            case(preg_match ('/^5[1-5]/', $cardNumber) >= 1):
                return CARD_TYPE_MASTERCARD;
            case(preg_match ('/^3[47]/', $cardNumber) >= 1):
                return CARD_TYPE_AEX;
            case(preg_match ('/^3(?:0[0-5]|[68])/', $cardNumber) >= 1):
                return CARD_TYPE_DINERS;
            case(preg_match ('/^6(?:011|5)/', $cardNumber) >= 1):
                return CARD_TYPE_DISCOVER;
            case(preg_match ('/^(?:2131|1800|35\d{3})/', $cardNumber) >= 1):
                return CARD_TYPE_JCB;
            default:
                return null;
                break;
        }
    }
    return null;
}
?>

No comments:

Post a Comment