php - 在 PHP 中验证信用卡的最佳方法是什么?

标签 php validation e-commerce numbers credit-card

给定一个信用卡号并且没有其他信息,在 PHP 中确定它是否是一个有效号码的最佳方法是什么?

现在我需要一些适用于 American Express、Discover、MasterCard 和 Visa 的东西,但如果它也适用于其他类型可能会有所帮助。

最佳答案

卡号的验证分三部分:

  1. PATTERN - 是否与发行人模式匹配(例如 VISA/Mastercard/等)
  2. CHECKSUM - 是否真的校验和(例如,不只是“34”之后的 13 个随机数使其成为美国运通卡号)
  3. 真的存在 - 它是否真的有一个关联的帐户(如果没有商家帐户,您不太可能得到这个)

图案

  • 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)
  • 等等。 ( detailed list of prefixes )

校验和

大多数卡片使用 Luhn 算法进行校验和:

Luhn Algorithm described on Wikipedia

Wikipedia 链接上有很多实现的链接,包括 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 - 在 PHP 中验证信用卡的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/174730/

相关文章:

php - 将文件上传到 SFTP 服务器

php - 如何使用此查询获取最多 10 行和 10 分钟的行?

php - jquery自动完成将不会显示数据

java - 验证逻辑应该在哪里?

javascript - 如何验证字母数字输入之间的空格

paypal - 如何将站点从电子商务重定向到 paypal 移动和桌面版本?

asp.net - 电子商务站点 : ASP. NET 还是 ASP.NET MVC?

php - 没有where子句的mysql动态查询

testing - 如何测试信用卡电子商务软件?

c# - 远程属性在 MVC ASP.NET 中不起作用