Last active
August 29, 2015 14:06
-
-
Save steinbring/ecd04800d9c68542d202 to your computer and use it in GitHub Desktop.
This code uses the Luhn formula to validate your credit card number. This acts as error detection, basicly. It could still be a fake number. I wrote this in PHP because the company is doing more PHP and I figure that I could use the practice. :)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
// What credit card number are we validating? | |
$CreditCardNumber = '5554172297437101'; | |
// Output the subject | |
echo $CreditCardNumber; | |
// Save the credit card number for later | |
$LastDigit = substr($CreditCardNumber, strlen($CreditCardNumber) - 1); | |
// Drop the last digit | |
$CreditCardNumber = substr_replace($CreditCardNumber ,"",-1); | |
// Reverse the string | |
$CreditCardNumber = strrev($CreditCardNumber); | |
// Convert the string to an array | |
$CreditCardNumber = str_split($CreditCardNumber); | |
// Multiply all the digits in odd positions by 2 | |
foreach ($CreditCardNumber as $index=>$char){ | |
if($index % 2 == 0){ | |
if($char * 2 <= 9){ | |
// If $char * 2 is less than or equal to 9, just add it | |
// Sum the numbers | |
$intSumOfNums = $intSumOfNums + $char * 2; | |
}else{ | |
// Else, subtract 9 from it | |
// Sum the numbers | |
$intSumOfNums = $intSumOfNums + ($char * 2) - 9; | |
} | |
}else{ | |
// If we are looking at an even digit, add it to our sum of numbers | |
$intSumOfNums = $intSumOfNums + $char; | |
} | |
} | |
// The check digit is the amount you need to add to that number to make a multiple of 10 | |
if(($intSumOfNums+$LastDigit) % 10 == 0) | |
echo ' is a valid credit card number'; | |
else | |
echo ' is not a valid credit card number'; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment