I found out that the right way to handle json data directly in PHP (via file_get_contents('php://input')
) is to make sure the request sets the right content-type i.e. Content-type: application/json
in the HTTP request header.
In my case I'm requesting pages from php using curl with to this code:
function curl_post($url, array $post = NULL, array $options = array()) {
$defaults = array(
CURLOPT_POST => 1,
CURLOPT_HEADER => 0,
CURLOPT_URL => $url,
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_TIMEOUT => 600
);
if(!is_null($post))
$defaults['CURLOPT_POSTFIELDS'] = http_build_query($post);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
if(($result = curl_exec($ch)) === false) {
throw new Exception(curl_error($ch) . "\n $url");
}
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
throw new Exception("Curl error: ".
curl_getinfo($ch, CURLINFO_HTTP_CODE) ."\n".$result . "\n");
}
curl_close($ch);
return $result;
}
$curl_result = curl_post(URL, NULL,
array(CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
CURLOPT_POSTFIELDS => json_encode($out))
);
Do note the CURLOPT_HTTPHEADER => array('Content-Type: application/json')
part.
On the receiving side I'm using the following code:
$rawData = file_get_contents('php://input');
$postedJson = json_decode($rawData,true);
if(json_last_error() != JSON_ERROR_NONE) {
error_log('Last JSON error: '. json_last_error().
json_last_error_msg() . PHP_EOL. PHP_EOL,0);
}
Do not change the max_input_vars
variable. Since changing the request to set right headers my issue with max_input_vars
went away. Apparently does not PHP evaluate the post variables with certain Content-type
is set.