php – How to json_decode an json array received from JavaScript?

php – How to json_decode an json array received from JavaScript?

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 doesnt 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. Its 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 short FILTER_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 use FILTER_SANITIZE_STRING.
The sensible way to validate a JSON string is to do json_decode and check if its null.

$jsonStr = filter_input(INPUT_GET, myparam); 
var_dump($jsonStr); 
var_dump(json_decode($jsonStr, true)); 

The mistake here is not about JSON, but lies in the request using encoded URI components.

If you use encodeURIComponent on the JS side, youll also have to use urldecode on the PHP side.

<?php
$jsonStr = %5B%22mystring1%22%2C%22mystring2%22%5D;
var_dump(
    json_decode(urldecode($jsonStr), true)
);

See: http://php.net/manual/en/function.urldecode.php

php – How to json_decode an json array received from JavaScript?

Leave a Reply

Your email address will not be published. Required fields are marked *