php - How to json_decode an json array received from JavaScript?
Get the solution ↓↓↓Solution:
I am tranfering a note from What does FILTER_SANITIZE_STRING do? but the entire accepted answer in that question explains it a lot better:
First -
php_filter_strip
. It doesn't do much, just takes the flags you pass to the function and processes them accordingly. It does the well-documented stuff.Then we construct some kind of map and call
php_filter_encode_html
. It's more interesting: it converts stuff like ", ', & and chars with their ASCII codes lower than 32 and higher than 127 to HTML entities, so & in your string becomes &. Again, it uses flags for this.Then we get call to
php_strip_tags_ex
, which just strips HTML, XML and PHP tags (according to its definition in /ext/standard/string.c) and removes NULL bytes, like the comment says.
(Emphasised the important part).
In shortFILTER_SANITIZE_STRING
will break your JSON because it will encode things that it should not. If you want to validate this input do not use this filter.
The answer here is to not useFILTER_SANITIZE_STRING
.
The sensible way to validate a JSON string is to dojson_decode
and check if it's null.
$jsonStr = filter_input(\INPUT_GET, 'myparam');
var_dump($jsonStr);
var_dump(json_decode($jsonStr, true));
Answer
Solution:
The mistake here is not about JSON, but lies in the request using encoded URI components.
If you useencodeURIComponent
on the JS side, you'll also have to useurldecode
on the PHP side.
<?php
$jsonStr = '%5B%22mystring1%22%2C%22mystring2%22%5D';
var_dump(
json_decode(urldecode($jsonStr), true)
);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: you must enable the openssl extension in your php.ini to load information from https://repo.packagist.org
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.