I'm using both PHP and Javascript to build some kind of web service. I try to validate a token calculated on post parameters, sent from JS to PHP. Let's say the code is as follows:
JS :
token = JSON.stringify(params);
PHP :
token = json_encode($_POST);
Can somebody please explain me why the two resulting JSON strings doesn't have the same length ?
(I tried to trim \n\r\t
in PHP, stripslashes in PHP, several JS libs) The PHP version of the string always have some more characters.
I was having the same issue where I wanted to compare an encrypted version of the encoded json string. To make the output of json_encode
identical to javascripts JSON.stringify
you can do this:
$php_string = json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
In JavaScript, a JSON key without quote is valid. In PHP, a JSON key without quote is NOT valid. (In fact, the right JSON syntax is with quotes on keys.)
So you’re right, the difference came from JSON.stringify
who strip the quotes from your integer key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With