萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 依信用卡規則隨機生成可驗證卡號(僅供學習)

前言

信用卡卡號遵循特定前綴規則與 Luhn 檢查碼機制。本文提供完整 PHP 類別,可依各大卡組織(Visa、MasterCard、Amex 等)規則生成符合 Luhn 校驗的測試卡號。嚴禁用於非法用途,僅供開發測試參考。

核心邏輯

  1. 定義各卡組織前綴清單(如 Visa 以 4 開頭,MasterCard 51-55 等)。
  2. 隨機選擇前綴,補齊隨機數字至指定長度減 1 位。
  3. 依 Luhn 演算法計算最後一位檢查碼並補全。

完整程式碼

<?php
class CreditCardGenerator {
    private $prefixLists = [
        'visa' => ["4539","4556","4916","4532","4929","40240071","4485","4716","4"],
        'mastercard' => ["51","52","53","54","55"],
        'amex' => ["34","37"],
        'discover' => ["6011"],
        'diners' => ["300","301","302","303","36","38"],
        'enroute' => ["2014","2149"],
        'jcb' => ["35"],
        'voyager' => ["8699"]
    ];

    public function generate($type, $length = 16, $count = 1) {
        if (!isset($this->prefixLists[$type])) return [];
        $prefixList = $this->prefixLists[$type];
        $results = [];
        for ($i = 0; $i < $count; $i++) {
            $prefix = $prefixList[array_rand($prefixList)];
            $results[] = $this->completeNumber($prefix, $length);
        }
        return $results;
    }

    private function completeNumber($prefix, $length) {
        $ccnumber = $prefix;
        while (strlen($ccnumber) < $length - 1) {
            $ccnumber .= mt_rand(0, 9);
        }
        // Luhn 計算檢查碼
        $sum = 0;
        $reversed = strrev($ccnumber);
        for ($pos = 0; $pos < $length - 1; $pos += 2) {
            $odd = $reversed[$pos] * 2;
            if ($odd > 9) $odd -= 9;
            $sum += $odd;
            if ($pos + 1 < $length - 1) {
                $sum += $reversed[$pos + 1];
            }
        }
        $checkdigit = ((floor($sum / 10) + 1) * 10 - $sum) % 10;
        return $ccnumber . $checkdigit;
    }
}

// 使用範例
$gen = new CreditCardGenerator();
echo "<h3>MasterCard</h3>";
echo implode('<br/>', $gen->generate('mastercard', 16, 5));
echo "<h3>Visa 16 位</h3>";
echo implode('<br/>', $gen->generate('visa', 16, 5));
echo "<h3>American Express</h3>";
echo implode('<br/>', $gen->generate('amex', 15, 3));
?>

輸出範例

MasterCard
5234123456789012
5412345678901234
...

Visa 16 位
4539123456789012
4916234567890123
...

法律聲明

生成的卡號僅能通過 Luhn 校驗,不代表真實有效卡號。任何盜刷、詐騙等非法行為均屬違法,後果自負。開發者應僅在測試環境使用。

copyright © 萬盛學電腦網 all rights reserved