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. <?php
  2. function is_valid_credit_card($s) {
  3. //defines a function
  4. $s = strrev(preg_replace('/[^\d]/','',$s));
  5. // remove non-digits and reverse so we are sure we won't mess up.
  6. $sum = 0;
  7. // compute checksum
  8. for ($i = 0, $j = strlen($s); $i < $j; $i++) {
  9. // Use even digits as-is
  10. if (($i % 2) == 0) {
  11. $val = $s[$i];
  12. // Use even digits as-is
  13. } else {
  14.  
  15. $val = $s[$i] * 2;
  16. if ($val > 9) { $val -= 9; }
  17. // Double odd digits and subtract 9 if greater than 9
  18. }
  19. $sum += $val;
  20. }
  21. return (($sum % 10) == 0);
  22. // number is valid if sum is a multiple of ten
  23. }
  24.  
  25. if (! is_valid_credit_card($_POST['credit_card'])) {
  26. //that is if else using the function we used to find it.
  27. echo' Sorry, that card number is invalid.';
  28. //if it's invalid
  29. }
  30. else
  31. }
  32. //else
  33. echo'That card number is valid.';
  34. //omg it is valid.
  35. {
  36. ?>


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
cyruswu's Avatar
Author:
Views:
2,532
Rating:
Posted on Wednesday 26th December 2007 at 10:48 AM
Oliver
Oliver's Avatar
Remember that in the script your just naming the function, the things that check are installed in PHP software.
Posted on Monday 24th December 2007 at 11:13 PM
cyruswu
cyruswu's Avatar
It checks the numbers inputten to that varraible $s.

Then, uses a bunch of ways to check the number given to see if it's valid. It just uses common sense of a credit card.
Posted on Monday 24th December 2007 at 04:53 PM
DanielXP
DanielXP's Avatar
Im guessing it checks the format of it.

Like a email something @ something . something
Posted on Monday 24th December 2007 at 03:56 PM
Dean
Dean's Avatar
how does this manage to validate a credit card :|?