Hello, today i was working with some PHP and AJAX, and i had a problem, finally i fixed it, but i was asking myself, why PHP works like this.
This ...
For further actions, you may consider blocking this person and/or reporting abuse
What about using the filter_input function from php?
Returns TRUE for "1", "true", "on" and "yes". Returns FALSE otherwise.
If FILTER_NULL_ON_FAILURE is set, FALSE is returned only for "0", "false", "off", "no", and "", and NULL is returned for all non-boolean values.
I am afraid that
FormData
will always convert your values to string, if it is not aBlob
or aFile
type.Check this StackOverflow answer, you solved your issue the right way, but I guess this has nothing to do with PHP (you would have the same issue with a NodeJS backend for instance).
Tips for your client side payload
You can take advantage of
JSON.stringify
to encode your data:Decode your payload seemlesly server side
I found this GitHub issue, with an interesting solution. I adapted it to make this seemless in your actual code:
Hope it helps!
PHP is how you get ants. :)
On a side note, all fields send in a post request are strings.
Use integers instead, then you can parse the string to a number, and check for 0 or 1.
Or use a JSON payload instead like Khalyomede suggests. ;)
JSON has boolean as a type
lmao your first sentence :')
I will started to use it, thnx dudes :)
Well since the dawn of time the following has held true:
false == 0
true != false
And of course "false" != 0 and must therefore be true.
This is also the reason for the following weirdness:
All HTTP 1.0/1.1 payload is string and integer values. Even binary files are BinHex'ed before transmitting.
If another language has booleans it's because it is converting the string for you. Will it do it for an online questionnaire? Answer a true/false question on a form and then save it to the database? Are you saving 0/1? Can't assume all answers will be boolean or ints? How about reports on the questionnaire? "98% answered 1". that will require the dev to flag the question as a boolean output then convert it back to a string.
Since you need to sanitize your data you should use the PHP filter_input library that was recommended by /mikcat.
Note: I am not lecturing or talking down to you but trying to provide you with the possible view of the PHP developers.
Not sure about PHP, but in most cases casting strings to booleans works like this: