Here’s a PHP function to validate credit card numbers using the Luhn algorithm (also known as the “modulus 10” or “mod 10” algorithm), which is commonly used to verify credit card numbers:
<?php
function validateCreditCard($cardNumber) {
// Remove any non-digit characters (e.g., spaces, dashes)
$cardNumber = preg_replace('/\D/', '', $cardNumber);
// Check if the card number length is between 13 and 19 digits
if (strlen($cardNumber) < 13 || strlen($cardNumber) > 19) {
return false;
}
// Luhn algorithm
$sum = 0;
$shouldDouble = false;
// Process each digit from right to left
for ($i = strlen($cardNumber) - 1; $i >= 0; $i--) {
$digit = $cardNumber[$i];
// Double every second digit
if ($shouldDouble) {
$digit *= 2;
// If doubling the digit results in a number greater than 9, subtract 9
if ($digit > 9) {
$digit -= 9;
}
}
// Add the digit to the sum
$sum += $digit;
// Toggle the flag
$shouldDouble = !$shouldDouble;
}
// A valid card number will have a total sum that is a multiple of 10
return ($sum % 10) === 0;
}
// Example usage:
$cardNumber = "4111111111111111";
if (validateCreditCard($cardNumber)) {
echo "Credit card number is valid.";
} else {
echo "Credit card number is invalid.";
}
?>
Explanation:
- Input Sanitization: Removes any non-numeric characters from the input.
- Luhn Algorithm: Calculates the checksum to validate the credit card number.
- Return Boolean: Returns
trueif the card number is valid andfalseotherwise.
This function works for most standard credit cards (Visa, MasterCard, etc.). However, it does not check specific card types or issuers.