| home / programming / carts / chap7 / 3 | [previous] |
|
|
If the number has met all of the preceding conditions, then we perform the
checksum test using the Luhn formula. First we make a copy of the number,
reversing the order of the digits, since it's easier to count them from left
to right, and store it in a variable named $copy:
$copy = strrev($cc_number);
Then we store its length as $length
and we initialise a running total $sum
to zero:
$length = strlen($cc_number);
$sum = 0;
for($c = 0; $c < $length; $c++)
{
As we add up the digits, we'll want to double every other digit starting
with the second one from the left, since we've reversed their order. Since
the first digit the first digit has the index 0, this means we'll be doubling
the odd-numbered ones. The first digit can be obtained as substr($digit,0,1), the second one as substr($digit,1,1), and so on through substr($digit,$length-1,1):
$digit = substr($copy,$c,1);
if($c % 2 == 1)
{
If the digit has an odd-numbered index in the string, we double it:
$digit *= 2;
Then we determine if the result is greater than 10. If it is, then it has
two digits (the highest possible value being 2 * 9 = 18), once again using
the substr()
function:
if($digit > 9)
{
$first = substr($digit,0,1);
$second = substr($digit,1,1);
$digit = $first + $second;
}
}
Now we increment the running total by the value of $digit
(which hasn't changed if the digit had an even-numbered index), and repeat
the process with the next digit until we've gone through all the digits in
$copy:
$sum += $digit;
}
Now we determine if the final value of $sum
is evenly divisible by 10. If it isn't, we know there was an error in the
number somewhere; we alert the customer accordingly and set the error flag
to FALSE:
if($sum % 10 != 0)
{
$err_msg .= "The $cc_type number failed to validate.
Please check the number on your card.<br />\n";
$validated = FALSE;
}
else
{
Finally, if the number's passed all of the above tests, we perform a check
on the expiration date indicated by the user to ensure that he hasn't given
us a date in the past. We obtain the number 1-12 for the current month and
the four-digit current year using date() and compare these to the values selected
in the form:
$thismonth = date("n");
$thisyear = date("Y");
if( $HTTP_POST_VARS["Expiration0Year_required"] == $thisyear
&&
$HTTP_POST_VARS["Expiration0Month_required"] < $thismonth )
{
If the year is the same as the current year but the month is previous to the current month, then we know we've got a problem, and we respond appropriately:
$err_msg .= "Invalid expiration date
(date indicated is in the past).<br />\n";
$validated = FALSE;
}
}
}
}
}
}
}
If we've passed through all of the tests in these code blocks, then we assume that the customer has given us the correct card number and expiration date.
| home / programming / carts / chap7 / 3 | [previous] |
Created: January 2, 2003
Revised: January 2, 2003
URL: http://webreference.com/programming/carts/chap7/3/4.html