Created
August 11, 2014 22:36
-
-
Save bndw/a1f4846ccdbe6e1b61da to your computer and use it in GitHub Desktop.
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 | |
/* | |
* Takes a credit card number and ensures | |
* it contains the proper number of digits | |
* for the given card type. | |
*/ | |
function isValidCreditCardNumber($cardNumber) | |
{ | |
// First check that the card number | |
// is a valid length. | |
$firstNumber = substr($cardNumber, 0, 1); | |
switch ($firstNumber) | |
{ | |
case 3: | |
// American Express | |
if (!preg_match('/^3\d{3}[ \-]?\d{6}[ \-]?\d{5}$/', $cardNumber)) | |
{ | |
return false; | |
} | |
break; | |
case 4: | |
// Visa | |
if (!preg_match('/^4\d{3}[ \-]?\d{4}[ \-]?\d{4}[ \-]?\d{4}$/', $cardNumber)) | |
{ | |
return false; | |
} | |
break; | |
case 5: | |
// MasterCard | |
if (!preg_match('/^5\d{3}[ \-]?\d{4}[ \-]?\d{4}[ \-]?\d{4}$/', $cardNumber)) | |
{ | |
return false; | |
} | |
break; | |
case 6: | |
// Discover | |
if (!preg_match('/^6011[ \-]?\d{4}[ \-]?\d{4}[ \-]?\d{4}$/', $cardNumber)) | |
{ | |
return false; | |
} | |
break; | |
default: | |
return false; | |
} | |
// All credit cards issued today are based on | |
// a modulus 10 algorithm, so we can use the | |
// Luhn Algorithm. | |
$cardNumber = str_replace('-', '', $cardNumber); | |
$map = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, | |
0, 2, 4, 6, 8, 1, 3, 5, 7, 9); | |
$sum = 0; | |
$last = strlen($cardNumber) - 1; | |
for ($i = 0; $i <= $last; $i++) | |
{ | |
$sum += $map[$cardNumber[$last - $i] + ($i & 1) * 10]; | |
} | |
if ($sum % 10 != 0) | |
{ | |
// Invalid card number | |
return false; | |
} | |
return true; | |
} | |
isValidCreditCardNumber('4111-1111-1111-1111'); // True | |
isValidCreditCardNumber('5558-545f-1234'); // False | |
isValidCreditCardNumber('9876-5432-1012-3456'); // False | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment