<?php // check card number if (!isset($_POST['card_number']) || empty($_POST['card_number'])) { print 'Please fill card number field'; exit; } elseif (!preg_match('/^\\d{16}$/', $_POST['card_number'])) { print 'Card number must contain 16 digits'; exit; } else { $card_number = (int) $_POST['card_number']; if (!is_valid_credit_card($card_number)) { print 'Incorrect card number'; exit; } } // check month field if (!isset($_POST['month']) || empty($_POST['month'])) { print 'Please fill month field'; exit; } elseif (!preg_match('/^(0[1-9]|1[0-2])$/', $_POST['month'])) { print 'Incorrect month'; exit; } else { $month = $_POST['month']; } // check year field if (!isset($_POST['year']) || empty($_POST['year'])) { print 'Please fill year field'; exit; } elseif (!preg_match('/^(1[7-9]|2[0-5])$/', $_POST['year'])) {
<?php function is_valid_credit_card($s) { // Remove non-digits and reverse $s = strrev(preg_replace('/[^\\d]/', '', $s)); // compute checksum $sum = 0; for ($i = 0, $j = strlen($s); $i < $j; $i++) { // Use even digits as-is if ($i % 2 == 0) { $val = $s[$i]; } else { // Double odd digits and subtract 9 if greater than 9 $val = $s[$i] * 2; if ($val > 9) { $val -= 9; } } $sum += $val; } // Number is valid if sum is a multiple of ten return $sum % 10 == 0; } if (!is_valid_credit_card($_POST['credit_card'])) { print 'Sorry, that card number is invalid.'; }