0

I'm creating a dummy payment page and checking if the credit card is 16 digits exactly in length and numerical only.

The problem is: If the credit card number is numerical and under 16digits it echo's ccno length, but also if the credit card number is valid (numerical and 16digits) it also echo's "ccno length".

 if (!preg_match("/^[0-9]{16}$/", $ccno)) {
       echo "ccno length";
     exit ();
  }

Thanks!

CJava
  • 189
  • 1
  • 5
  • 15
  • Code works fine for 16-digits card nums and doesn't echo anything, for other nums it echo `ccno length`. Check it once again. – u_mulder Mar 22 '14 at 13:36
  • You could just as easily do `strleng($ccno) && is_numerical($ccno)`. Also note there are already ways to determine valid credit numbers. – Jared Farrish Mar 22 '14 at 13:36
  • @JaredFarrish: The problem with this approach is that `is_numeric` returns true for a string with a decimal number. – Casimir et Hippolyte Mar 22 '14 at 13:39
  • `is_numeric` would indeed by a poor choice here, but [`ctype_digit()`](http://php.net/ctype_digit) would be perfect. – IMSoP Mar 22 '14 at 13:41
  • @CasimiretHippolyte - Yes, I was a bit premature. [`if ((int) $ccno != $ccno || strlen($ccno) !== 16)`](http://codepad.viper-7.com/XPCRGJ) – Jared Farrish Mar 22 '14 at 13:45
  • Your code appears to work fine for me; maybe `$ccno` doesn't contain what you think it does. [Here's a demo showing the check working OK](http://codepad.viper-7.com/PAgWUR). – IMSoP Mar 22 '14 at 13:45
  • have tried this and it still doesnt work: if ((strlen($ccno) == 16) && is_digits($ccno)){ echo "good"; exit(); } – CJava Mar 22 '14 at 13:46
  • @CJava: the reason is that `is_int` returns true only for a int type and returns false for a string. – Casimir et Hippolyte Mar 22 '14 at 13:48
  • 1
    @CJava What is `is_digits`? – IMSoP Mar 22 '14 at 13:48
  • @IMSoP that checks its numerical without decimal places. the strlen returns 0 when its 16digits – CJava Mar 22 '14 at 13:50
  • @CJava My point was that it's not a built-in PHP function, so we have no way of seeing if it works or not. However, to reiterate **the code you've posted here [works fine](http://php.net/ctype_digit)**, even if it's not the best approach. The bug lies elsewhere in your code. Try `var_dump($ccno)` to see what value it actually has. – IMSoP Mar 22 '14 at 13:52

0 Answers0