What do we actually mean when we say "validate a credit card
number"? Quite simply it means that we run a credit card number
through a special algorithm known as the Mod 10 algorithm.
This algorithm processes some simple numerical data validation
routines against the number and the result of this algorithm
can be used to determine whether or not a credit card number
is valid. There are several different types of credit cards
that one can use to make a purchase, however they can all be
validated using the Mod 10 algorithm.
As well as passing the Mod 10 algorithm, a credit card number
must also pass several different formatting rules. A list of
these rules for each of the six most popular credit cards is
shown below: Mastercard: Must have a prefix of 51 to 55, and
must be 16 digits in length. Visa: Must have a prefix of 4,
and must be either 13 or 16 digits in length. American Express:
Must have a prefix of 34 or 37, and must be 15 digits in length.
Diners Club: Must have a prefix of 300 to 305, 36, or 38, and
must be 14 digits in length. Discover: Must have a prefix of
6011, and must be 16 digits in length. JCB: Must have a prefix
of 3, 1800, or 2131, and must be either 15 or 16 digits in length.
As mentioned earlier, in this article we will be creating a
PHP class that will hold the details of a credit card number
and expose a function indicating whether or not the number of
that credit card is valid (i.e. whether it passed the Mod 10
algorithm or not). Before we create that class however, let's
look at how the Mod 10 algorithm works.
The Mod 10 algorithm There are three steps that the Mod 10 algorithm
takes to determine whether or not a credit card number is valid.
We will use the valid credit card number 378282246310005 to
demonstrate these steps:
Step One The number is reversed and the value of every second
digit is doubled, starting with the digit in second place:
378282246310005
... becomes ...
500013642282873
and the value of every second digit is doubled:
5 0 0 0 1 3 6 4 2 2 8 2 8 7 3 x2 x2 x2 x2 x2 x2 x2
-------------------------------------------
0 0 6 8 4 4 14
Step Two The values of the numbers that resulted from multiplying
every second digit by two are added together (i.e. in our example
above, multiplying the 7 by two resulted in 14, which is 1 +
4 = 5). The result of these additions is added to the value
of every digit that was not multiplied (i.e. the first digit,
the third, the fifth, etc):
5 + (0) + 0 + (0) + 1 + (6) + 6 + (8) + 2 + (4) + 8 + (4) +
8 + (1 + 4) + 3
= 60
Step Three When a modulus operation is applied to the result
of step two, the remainder must equal 0 in order for the number
to pass the Mod 10 algorithm. The modulus operator simply returns
the remainder of a division, for example:
10 MOD 5 = 0 (5 goes into 10 two times and has a remainder of 0)
20 MOD 6 = 2 (6 goes into 20 three times and has a remainder of 2)
43 MOD 4 = 3 (4 goes into 43 ten times and has a remainder of 3)
So for our test credit card number 378282246310005, we apply
a modulus of 10 to the result from step two, like this:
60 MOD 10 = 0
The modulus operation returns 0, indicating that the credit
card number is valid.
Now that we understand the Mod 10 algorithm, it's really quite
easy to create our own version to validate credit card numbers
with PHP. Let's create our credit card class now.
Creating the CCreditCard Class
Let's now create a PHP class that we can use to store and validate
the details of a credit card. Our class will be able to hold
the cardholder's name, the card type (mastercard, visa, etc),
the card number, and the expiry month and date.
Create a new PHP file called class.creditcard.php. As we walk
through the following two pages, copy-paste each piece of code
shown to the file and save it.
We start of by defining several card type constants. These values
will be used to represent the type of card that our class will
be validating:
<?php
define("CARD_TYPE_MC", 0);
define("CARD_TYPE_VS", 1);
define("CARD_TYPE_AX", 2);
define("CARD_TYPE_DC", 3);
define("CARD_TYPE_DS", 4);
define("CARD_TYPE_JC", 5);
Next, we have our class declaration. Our class is called CCreditCard.
Note that there is an extra 'C' at the front of the class name
intentionally: it's a common programming practice to prefix
the name of a class with 'C' to in fact indicate that it is a class.
We also define five member variables, which will be used internally
to hold the credit card's name, type, number, expiry month and
year respectively:
class CCreditCard
else
To make our CCreditCard class flexible, it accepts several different
ways to specify the type of card that is being stored. For example,
if we want to add the details of a mastercard to a new instance
of our CCreditCard class, then we could pass in the following
values for the $type variable of the constructor: "mc", "mastercard",
"m", or "1".
We make sure that a valid card type has been passed in, and
set the value of our classes $__ccType variable to one of the
constant card type values that we defined earlier:
// Make sure card type is valid
switch(strtolower($type))
case 'vs':
case 'visa':
case 'v':
case '2':
case 'ax':
case 'american express':
case 'a':
case '3':
case 'dc':
case 'diners club':
case '4':
case 'ds':
case 'discover':
case '5':
case 'jc':
case 'jcb':
case '6':
default: }
If an invalid card type is passed in, then the default branch
of our switch statement will be called, resulting in our script
terminating with the die() function.
We can take advantage of PHP's built-in support for regular
expressions by using the ereg_replace function to strip out
all non-numeric characters from the credit card number:
// Don't check the number yet, just kill
all non numerics
if(!empty($num))
else
}
else
We finish off our CCreditCard constructor by making sure that
both the expiry month and year are valid, numerical values:
if(!is_numeric($expm)
|| $expm
< 0 || $expm
> 12)
else
// Get the current year
$currentYear = date('Y'); settype($currentYear,
'integer');
if(!is_numeric($expy)
|| $expy
< $currentYear ||
$expy > $currentYear
+ 10)
else
}
Creating the CCreditCard Class (contd.)
In our CCreditCard class, the only way to set the values of
the credit cards details is through the constructor. To actually
retrieve the values of our class specific variables ($__ccName,
$__ccType, etc), we create several functions, like this:
function Name()
function Type()
case CARD_TYPE_VS:
case CARD_TYPE_AX:
case CARD_TYPE_DC:
case CARD_TYPE_DS:
case CARD_TYPE_JC:
default:
}
function Number()
function ExpiryMonth()
function ExpiryYear()
These functions allow us to retrieve the values of the variables
contained within our class. For example, If I created an instance
of our CCreditCard class called $cc1, then I could retrieve
its expiration month using $cc1->ExpiryMonth().
A common function when working with credit cards is displaying
the details that you've captured from that user back to them
as a confirmation. For example, if the user entered a credit
card number of 4111111111111111, then you might want to only
show part of the number to them, such as 4111111111111xxxx.
Our CCreditCard class contains a function called SafeNumber,
which accepts two arguments. The first is the character to mask
the digits with, and the second is the number of digits to mask
(from the right):
function SafeNumber($char
= 'x', $numToHide = 4)
if($numToHide
> 10)
$cardNumber = $this->__ccNum;
$cardNumber = substr($cardNumber,
0, strlen($cardNumber) - $numToHide);
for($i
= 0; $i < $numToHide;
$i++)
return $cardNumber;
}
If we had an instance of our CCreditCard class called $cc1 and
the credit card number stored in this class was 4242424242424242,
then we could mask the last 6 digits like this:
echo $cc1->SafeNumber('x',
6).
The last function contained in our CCreditCard class is called
IsValid, and implements the Mod 10 algorithm against the credit
card number of our class, returning true/false.
It starts of by setting two variables ($validFormat
and $passCheck) to false:
function IsValid() $
",
At this point, $validFormat will be true (ereg returns true/false)
if the credit card number is in the correct format, and false
if it's not.
We now implement a PHP version of the Mod 10 algorithm, using
exactly the same steps that we described earlier:
The $numSum variable will contain the sum of all of the variables
from step two of the Mod 10 algorithm, which we described earlier.
PHP's symbol for the modulus operator is '%', so we assign true/false
to the $passCheck variable, depending on whether or not $numSum
has a modulus of zero:
If both $validFormat and $passCheck are true, then we return
true, indicating that the card number is valid. If not, we return
false, indicating that either the card number was in an incorrect
format, or if failed the Mod 10 check:
And that's all there is to our CCreditCard class! Let's now
look at a simple validation example using HTML forms, PHP, and
an instance of our CCreditCard class.
Run the script in your browser. Here are two screen shots from
my browser. The first one shows the HTML form, and the second
shows the output once the form is submitted:
If you're thinking of setting up an eCommerce site which will
process/store visitors credit card details, then you should
take the class we've just made and customize it to suit your
needs. You might want to add other functions to it to compare
CCreditCard objects, format the cards details into an XML string,
encrypt the cards details to a database, or even process the
payment in real time.
About the Author:
David Rusik FREE programming eBooks? Want
to learn XML, Java, Visual Basic, HTML, or how to promote your
site for free? Our collection of free eBook downloads might
be just the thing you need. Ready to download? Visit http://www.devarticles.com/ebooks.php
now!