在PHP中验证信用卡的最佳方法是什么？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (42)

2 个回答

1. 花纹-是否符合发行人的模式(例如VISA/Mastercard/等)。
2. 校验和-它是否实际检查和(例如，在“34”之后不只是13个随机数使其成为AMEX卡号)。
3. 真的存在-它是否真的有一个相关的帐户(如果没有商人帐户，你不太可能得到这个帐户)。

花纹

• MASTERCARD前缀=51-55，长度=16(Mod10校验和)
• Visa前缀=4，长度=13或16(MOD 10)
• Amex前缀=34或37，长度=15(Mod10)
• Dinner Club/Carte Prefix前缀=300-305，36或38，长度=14(MOD 10)
• Discover前缀=6011，622126-622925，644-649，65，长度=16(Mod10)

校验和

```<?
/* Luhn algorithm number checker - (c) 2005-2008 shaman - www.planzero.org *
* This code has been released into the public domain, however please      *
* give credit to the original author where possible.                      */

function luhn_check(\$number) {

// Strip any non-digits (useful for credit card numbers with spaces and hyphens)
\$number=preg_replace('/\D/', '', \$number);

// Set the string length and parity
\$number_length=strlen(\$number);
\$parity=\$number_length % 2;

// Loop through each digit and do the maths
\$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 (in effect)
if (\$digit > 9) {
\$digit-=9;
}
}
// Total up the digits
\$total+=\$digit;
}

// If the total mod 10 equals 0, the number is valid
return (\$total % 10 == 0) ? TRUE : FALSE;

}
?>```

```function check_cc(\$cc, \$extra_check = false){
\$cards = array(
"visa" => "(4\d{12}(?:\d{3})?)",
"amex" => "(3[47]\d{13})",
"jcb" => "(35[2-8][89]\d\d\d{10})",
"maestro" => "((?:5020|5038|6304|6579|6761)\d{12}(?:\d\d)?)",
"solo" => "((?:6334|6767)\d{12}(?:\d\d)?\d?)",
"mastercard" => "(5[1-5]\d{14})",
"switch" => "(?:(?:(?:4903|4905|4911|4936|6333|6759)\d{12})|(?:(?:564182|633110)\d{10})(\d\d)?\d?)",
);
\$names = array("Visa", "American Express", "JCB", "Maestro", "Solo", "Mastercard", "Switch");
\$matches = array();
\$pattern = "#^(?:".implode("|", \$cards).")\$#";
\$result = preg_match(\$pattern, str_replace(" ", "", \$cc), \$matches);
if(\$extra_check && \$result > 0){
\$result = (validatecard(\$cc))?1:0;
}
return (\$result>0)?\$names[sizeof(\$matches)-2]:false;
}```

```\$cards = array(
"4111 1111 1111 1111",
);

foreach(\$cards as \$c){
\$check = check_cc(\$c, true);
if(\$check!==false)
echo \$c." - ".\$check;
else
echo "\$c - Not a match";
echo "<br/>";
}```

`4111 1111 1111 1111 - Visa`