0

I have the following situation:

<select name="n">
    <option>Please fill</option>
    <option value="0">0</option>
    <option value="1">1</option>
</select>

Now, i pass the serialized form with Ajax. I correctly see this in the console's POST panel:

[...]&n=0&[...]

My php validation script check both if the field has been filled and, for security reasons, that it is a digit:

parse_str($_REQUEST['data'], $values);
if (!ctype_digit($values['n'])) {
    array_push($err, 'n');
}

Can someone explain WHY if i'm passing the value 0 this check always fails? If i pass any other select option with a digit other than 0, it let me in... I tried also using is_numeric instead of ctype_digit (just to try) and it fails as well. But this makes no sense...as 0 is both numeric and digit!

UPDATE if i var_dump($values['n']), i get that it is null...so is there any problem with the parse_str($_REQUEST['data'], $values)?

Mariano
  • 221
  • 1
  • 4
  • 14
  • The `!` character itself is a negation, not a comparison. To @deceze answer I'd also add `intval()` somewhere. – Daniel W. Mar 27 '14 at 09:46
  • 1
    @DanFromGermany why shuld i add intval() when ctype_digit() already returns false on all entry that are not digits (including float numbers both with dot or comma)? – Mariano Mar 27 '14 at 09:49

1 Answers1

3

Both 0 and '0' (as integer and as string) are considered false. So !$values['n'] is true. ctype_digit works just fine. You probably want to check for !isset($values['n']) instead of !$values['n'].

deceze
  • 510,633
  • 85
  • 743
  • 889
  • thanks, it worked with isset but with var_dump($values['n']) it says me that it is null...so i guess the problem is in the parse_str()? – Mariano Mar 27 '14 at 09:53
  • Why aren't you using `$_GET['n']`/`$_POST['n']` to begin with...? – deceze Mar 27 '14 at 09:59
  • cause my form is a lot more complex then the part i've posted and with the parse_str i get all the variables with only 1 line of code. also, as `data` is a string passed by ajax, i can't use $_POST – Mariano Mar 27 '14 at 11:42