Last active
December 20, 2022 16:36
-
-
Save prezine/81ca09487e188ba9070f4e888ef5bdef to your computer and use it in GitHub Desktop.
Credit Card Validation in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Card { | |
public function getCCType($cardNumber) { | |
// Remove non-digits from the number | |
$cardNumber = preg_replace('/\D/', '', $cardNumber); | |
// Validate the length | |
$len = strlen($cardNumber); | |
if ($len < 15 || $len > 16) { | |
throw new Exception("Invalid credit card number. Length does not match"); | |
} else { | |
switch($cardNumber) { | |
case(preg_match ('/^4/', $cardNumber) >= 1): | |
return 'Visa'; | |
case(preg_match ('/^5[1-5]/', $cardNumber) >= 1): | |
return 'Mastercard'; | |
case(preg_match ('/^3[47]/', $cardNumber) >= 1): | |
return 'Amex'; | |
case(preg_match ('/^3(?:0[0-5]|[68])/', $cardNumber) >= 1): | |
return 'Diners Club'; | |
case(preg_match ('/^6(?:011|5)/', $cardNumber) >= 1): | |
return 'Discover'; | |
case(preg_match ('/^(?:2131|1800|35\d{3})/', $cardNumber) >= 1): | |
return 'JCB'; | |
default: | |
throw new Exception("Could not determine the credit card type."); | |
break; | |
} | |
} | |
} | |
public function validateChecksum($number) { | |
// Remove non-digits from the number | |
$number=preg_replace('/\D/', '', $number); | |
// Get the string length and parity | |
$number_length = strlen($number); | |
$parity = $number_length % 2; | |
// Split up the number into single digits and get the total | |
$total=0; | |
for ($i=0; $i<$number_length; $i++) { | |
$digit=$number[$i]; | |
// Multiply alternate digits by two | |
if ($i % 2 == $parity) { | |
$digit*=2; | |
// If the sum is two digits, add them together | |
if ($digit > 9) { | |
$digit-=9; | |
} | |
} | |
// Sum up the digits | |
$total+=$digit; | |
} | |
// If the total mod 10 equals 0, the number is valid | |
return ($total % 10 == 0) ? TRUE : FALSE; | |
} | |
} | |
$card = new Card(); | |
echo $card->validateChecksum(xxxx-xxxx-xxxx-xxxx) // 1 or 0 | |
echo $card->getCCType(xxxx-xxxx-xxxx-xxxx) // Visa, Mastercard, Amex, Diners, Discover, JCB |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment