本文介绍了用PHP验证信用卡的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出一个信用卡号但没有其他信息,PHP中确定它是否为有效号码的最佳方法是什么?
Given a credit card number and no additional information, what is the best way in PHP to determine whether or not it is a valid number?
现在,我需要可以与American Express,Discover,MasterCard和Visa一起使用的功能,但是如果它也可以与其他类型的功能一起使用,则可能会有所帮助.
Right now I need something that will work with American Express, Discover, MasterCard, and Visa, but it might be helpful if it will also work with other types.
推荐答案
卡号验证分为三个部分:
There are three parts to the validation of the card number:
- 模式-它是否与发行人模式(例如VISA/Mastercard/etc)相匹配
- CHECKSUM (校验和)-它是否实际进行校验和(例如,将"34"后面的13个随机数字用作美国运通卡号)
- 真的存在-它确实有一个关联帐户(如果没有商家帐户,您不太可能获得此帐户)
- PATTERN - does it match an issuers pattern (e.g. VISA/Mastercard/etc.)
- CHECKSUM - does it actually check-sum (e.g. not just 13 random numbers after "34" to make it an AMEX card number)
- REALLY EXISTS - does it actually have an associated account (you are unlikely to get this without a merchant account)
模式
- 主卡前缀= 51-55,长度= 16(Mod10校验和)
- VISA前缀= 4,长度= 13或16(Mod10)
- AMEX前缀= 34或37,长度= 15(Mod10)
- Diners Club/Carte Prefix = 300-305,36或38,长度= 14(Mod10)
- Discover Prefix = 6011,622126-622925,644-649,65,Length = 16,(Mod10)
- 等(详细的前缀列表)
- MASTERCARD Prefix=51-55, Length=16 (Mod10 checksummed)
- VISA Prefix=4, Length=13 or 16 (Mod10)
- AMEX Prefix=34 or 37, Length=15 (Mod10)
- Diners Club/Carte Prefix=300-305, 36 or 38, Length=14 (Mod10)
- Discover Prefix=6011,622126-622925,644-649,65, Length=16, (Mod10)
- etc. (detailed list of prefixes)
Pattern
大多数卡将Luhn算法用于校验和:
Most cards use the Luhn algorithm for checksums:
Wikipedia链接上有许多实现的链接,包括PHP:
There are links to many implementations on the Wikipedia link, including 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;
}
?>
这篇关于用PHP验证信用卡的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!