php Implementation of Credit Card Check Bit Algorithm THE LUHN MOD 10 Example

  • 2021-06-28 08:58:58
  • OfStack

According to the algorithm The Luhn Mod-10 Method for checkpoint of payment card in ISO 2894:

1. Multiply the weight of each digit on the card number.The rule is that if the number of card numbers is even, the first digit is multiplied by 2, otherwise multiplied by 1, and then, 1,2,1,2 respectively;
2. If each digit is multiplied by its weight and exceeds 9, then 9 needs to be subtracted;
3. Sum all the processed weighted numbers and use the number 10 to solve the modulus;
4. The remainder should be 0, otherwise it may be an input error.It may also be a false number.
With a simple implementation of PHP, the actual scene front end is verified a little better, such as JS.


 function check_card($card){  
    if (!is_numeric($card)) return False;  
    $card_len = strlen($card);  
    $i = 0;  
    $num_i = array();  
    do{  
        if (!$i){  
            $num_x = $card_len % 2 ? 1 : 2;  
        } else {  
            $num_x = $num_x == 1 ? 2 : 1;      
        }  
        $num_i[$i] = (int)$card[$i] * $num_x;  
        $num_i[$i] = $num_i[$i] > 9 ? $num_i[$i] - 9 : $num_i[$i];  

    }while(isset($card[++$i]));  
    $num_sum = array_sum($num_i);  
    return $num_sum % 10 ? False : True;  
}  
 


Related articles: