Tuesday, September 6, 2011

PHP Credit Card Validation Function


This PHP function checks the validity of a credit card specified by the supplied parameters containing the card number and card type.
The specifications for valid credit cards have been taken from various sources on the web. The commonest credit cards are are supported in this implementation, but more may be added as required. One of the advantages of this routine is the ease with which additional cards may be added, as it is totally data driven.
Try the routine. Although no attempt is made to capture the input, it is suggested that you don't provide the number of your own credit card. The following are credit card numbers in a valid format:


American Express3400 0000 0000 009
Carte Blanche3000 0000 0000 04
Discover6011 0000 0000 0004
Diners Club3852 0000 0232 37
enRoute2014 0000 0000 009
JCB3566 0020 2036 0505
MasterCard5500 0000 0000 0004
Solo6334 0000 0000 0004
Switch4903 0100 0000 0009
Visa4111 1111 1111 1111
Laser6304 1000 0000 0008


The function returns true or false, depending on whether the credit card name / number combination is found to be valid. If it is not valid, a numeric code is returned in one parameter, and error text returned in another as may be seen in the demonstration.
The credit card details are held in an array within the function, and additional cards may be readily added. The format of the array is as follows:

array ('name' => 'Visa', 
       'length' => '13,16', 
       'prefixes' => '4',
       'checkdigit' => true)
  • name is the name of the credit card as supplied by the user.
  • length is a comma separated list of the number of valid digits in the associated card number. Thus in the above example, Visa cards may have either 13 or 16 digits.
  • prefixes is a comma separated list of the valid prefixes in the associated card number. In the above example, Visa cards must start with the digit "4".
  • checkdigit is a boolean value of true or false that indicates whether the last character of the credit card number is a modulus 10 check digit.
Download compressed PHP file (2,623 bytes)