4 ms·
The '123n'==123 conversion is the cause for at least 8 very nasty bugs in validating user input in that application I was referring to. And the fact that when
by pilif 16y ago
The '123n'==123 conversion is the cause for at least 8 very nasty bugs in validating user input in that application I was referring to.
And the fact that when comparing integer to strings, PHP prefers to convert the string to compare instead of converting the number (which would be lossless)
- wvenable 16y agoIf you care about numbers in your application, wouldn't the very first test in validating user input would be an is_numeric() call? In my opinion, you have to be doing a lot of other things incorrectly for this to be a real problem.
- pilif 16y agois_numeric doesn't help you if you want to find out whether the value in $foobar is a string that represents an integer or not. The only way to safely do that in PHP is, sadly, a regular expression. is_int checks the type, so is_int('1234') is as false as is_int('123n') or is_int('abc') is_numeric is too permissive as it allows floating point numbers or even hexadecimal values. intval($foobar) == $foobar doesn't work due to intval('123n') == 123 intval($foobar) === $foobar naturally doesn't work because the types don't match. The code in question is the receiving end of some machine generated communication that is supposed to closely follow a specification. During validation if the spec says that it requires a base10 integer encoded in ASCII, then 0xFF isn't permissible just because is_numeric() says so.
- wvenable 16y agoI have this function in my own code. You can adjust it's permissiveness your taste: function is_intval($value) { if (is_integer($value)) return true; if (is_bool($value)) return true; if (!is_numeric($value)) return false; if (is_float($value) && floatval(intval($value)) == $value) return true; if (is_string($value) && strval(intval($value)) == $value) return true; return false; }
- pilif 16y ago... hereby proving my point that PHP's default conversions are a bit... strange.
- wvenable 16y agoI never said it wasn't weird!! I just said that it's not really a practical problem in most cases. Perhaps you do have to be extra careful and I'm just so used to it that I don't give it a second thought.