關於 PHP, Linux, Open Source 及個人生活記載的網誌。
RSS icon
  • PHP 檢查信用卡號碼

    Posted on August 26th, 2007 Sam Tang No comments

    現在網上購物越來越普及,所以對信用卡號碼的檢查也變得重要。要檢查信用卡號碼,一般可以用 LUHN 演算法來實現。現在大部份的主要信用卡也是使用 LUHN 演算法,包括 Visa, Master Card, American Express 及 Discover 等。LUHN 演算法只可以檢查信用卡號碼的合法性,而不會檢查信用卡其他資訊,包括是否過期。使用方法為:

    1. 檢查信用卡號碼是否 16 位。
    2. 將信用卡號碼切割成 16 個個別數字。
    3. 將上面切割得的所有數字,由左至右起計,每逄單數位置的數值乘 2。
    4. 將加總後所有結果都切割成個別數字再相加。
    5. 將上面求得的總數求出 10 的餘數,如果餘數是 0 便表示信用卡號碼正確,否則便是錯誤。

    以下是 PHP 使用 LUHN 演算法檢查信用卡號碼的函式:

    PHP:
    1. <?php
    2. /* luhn_checker(): This is a small PHP function for checking valid *
    3. * credit card with LUHN algorithm                                  *
    4. *                                                                  *
    5. * Last updated: 26 August 2007                                     *
    6. * This is a free PHP script under GNU GPL version 2.0 or above     *
    7. * Copyright (C) 2007 Sam Tang                                      *
    8. * Feedback/comment/suggestions : http://www.real-blog.com/        */
    9.  
    10. function luhn_checker($card_num){
    11.     // 將非數字的字串移除
    12.     $card_num = preg_replace("/\D|\s/", "", $card_num);
    13.  
    14.     $sum = 0;
    15.     for($i=0; $i<strlen($card_num); $i++){
    16.         $digit = substr($card_num, $i, 1);
    17.         if(($i % 2) == 0){
    18.             // 在單數位置的數值乘 2
    19.             $digit = $digit * 2;
    20.         }
    21.  
    22.         if ($digit> 9)  $digit = $digit - 9;
    23.         $sum += $digit;
    24.     }
    25.  
    26.     if(($sum % 10) == 0 && strlen($card_num) == 16){
    27.         return TRUE;
    28.     }else{
    29.         return FALSE;
    30.     }
    31. }
    32.  
    33. /* Example
    34. if(luhn_checker("1234567812345678")){
    35.     echo "Correct!";
    36. }else{
    37.     echo "Wrong card number!";
    38. }
    39. */
    40. ?>

    檔案下載: luhn_checker


    Leave a reply

    *
    To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
    Click to hear an audio file of the anti-spam word