Validating Credit Cards
Hello, everyone.
I wasted my time learning more php to give you this tutorial.
So, here is a example:
PHP Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
function is_valid_credit_card($s) {
//defines a function
$s = strrev(preg_replace('/[^\d]/','',$s));
// remove non-digits and reverse so we are sure we won't mess up.
$sum = 0;
// compute checksum
for ($i = 0, $j = strlen($s); $i < $j; $i++) {
// Use even digits as-is
if (($i % 2) == 0) {
$val = $s[$i];
// Use even digits as-is
} else {
$val = $s[$i] * 2;
if ($val > 9) { $val -= 9; }
// Double odd digits and subtract 9 if greater than 9
}
$sum += $val;
}
return (($sum % 10) == 0);
// number is valid if sum is a multiple of ten
}
if (! is_valid_credit_card($_POST['credit_card'])) {
//that is if else using the function we used to find it.
echo' Sorry, that card number is invalid.';
//if it's invalid
}
else
}
//else
echo'That card number is valid.';
//omg it is valid.
{
?>
You have to the put is_valid_credit_Card function in your code. For the if else to work.
I also use $_POST[credit_card]. As the credit number varriable. So, you can change that if you want.
Now, you know how to valid credits cards. This is pretty much useful for advanced progamrers.
Thanks for reading,
Cyrus Wu