给定一个信用卡号码并且没有其他信息,PHP 中确定它是否是有效号码的最佳方法是什么?
现在我需要一些可以与美国运通卡、Discover、万事达卡和维萨卡一起使用的东西,但如果它也可以与其他类型一起使用,那可能会有所帮助。
卡号验证分为三个部分:
-
PATTERN- 是否与发卡机构模式匹配(例如 VISA/Mastercard/等)
-
CHECKSUM- 它实际上是否校验和(例如,不仅仅是“34”后面的 13 个随机数字使其成为 AMEX 卡号)
-
真实存在- 它实际上是否有关联帐户(如果没有商家帐户,您不太可能获得此帐户)
Pattern
- MASTERCARD 前缀=51-55,长度=16(Mod10 校验和)
- VISA 前缀=4,长度=13 或 16 (Mod10)
- AMEX 前缀=34 或 37,长度=15 (Mod10)
- Diners Club/Carte 前缀=300-305、36 或 38,长度=14 (Mod10)
- 发现前缀=6011,622126-622925,644-649,65,长度=16,(Mod10)
- etc. (前缀详细列表)
Checksum
大多数卡使用 Luhn 算法进行校验和:
维基百科上描述的 Luhn 算法
维基百科链接上有许多实现的链接,包括 PHP:
<?
/* 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;
}
?>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)