This is a simple PHP script that validates a credit card number using the Luhn algorithm and identifies the card's provider.
- Set the variable $ccd to the credit card number you want to validate.
- Run the script. The script will output a JSON object with the validation status and card provider.
The script consists of two main functions: checkCard()
and cardProvider()
.
The checkCard()
function checks whether the provided credit card number is valid using the Luhn algorithm. The Luhn algorithm works as follows:
- Double the value of every second digit from the right.
- If the result of this doubling operation is greater than 9 (e.g., 8 * 2 = 16), then subtract 9 from that result (e.g., 16 - 9 = 7).
- Sum all the digits.
- If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; otherwise, it is not valid.
The
checkCard()
function implements these steps and returns true if the number is valid, and false otherwise.
The cardProvider()
function determines the credit card provider based on the starting digits of the card number. The function uses regular expressions to match these starting digits. The current implementation can identify Visa, MasterCard, American Express, Diners Club, and Discover cards.
The script outputs a JSON object with the following fields:
creditCardNumber
: The input credit card number.isValid
: A boolean value indicating whether the card number is valid.provider
: The card provider.
The Content-Type header is set to application/json for proper handling of the output.
For the credit card number '5105 1051 0510 5100', the script will output:
{
"creditCardNumber": "5105 1051 0510 5100",
"isValid": true,
"provider": "MasterCard"
}