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 Express||3400 0000 0000 009|
|Carte Blanche||3000 0000 0000 04|
|Discover||6011 0000 0000 0004|
|Diners Club||3852 0000 0232 37|
|enRoute||2014 0000 0000 009|
|JCB||3566 0020 2036 0505|
|MasterCard||5500 0000 0000 0004|
|Solo||6334 0000 0000 0004|
|Switch||4903 0100 0000 0009|
|Visa||4111 1111 1111 1111|
|Laser||6304 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 (3,195 bytes)
Note: This routine was last updated on 17th October 2012 to correct a Diners Club bug. Thanks to Pietro Cerri.