Type of “application/json” prevents post variables from being sent

こ雲淡風輕ζ 提交于 2019-12-19 04:00:09

问题


I've found that if I try a PHP POST curl, the postvars are sent fine. Once I add the httpheader of content-type: application/json the postvars don't go across any more. I've tried the postvars as a JSON string and as a query string.

Showing some code:

$ch = curl_init();

$post =  json_encode(array('p1' => 'blahblahblah', 'p2' => json_encode(array(4,5,6))));

$arr = array();
array_push($arr, 'Content-Type: application/json; charset=utf-8');

curl_setopt($ch, CURLOPT_HTTPHEADER, $arr);
curl_setopt($ch, CURLOPT_URL, 'https://example.com/file.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

curl_exec($ch);
curl_close($ch);

回答1:


A real HTTP Post, that gets broken into an array automagically by PHP must be formatted in name=value pairs, the best way to do this in PHP is using the http_build_query function.

http://ca2.php.net/manual/en/function.http-build-query.php

There is an example that works in the PHP Manual using curl:

http://ca2.php.net/manual/en/function.curl-exec.php#98628

What you're doing is a 'RAW' post, see this other question:

How to post JSON to PHP with curl

A quick snippet to get the RAW Json data.

<?php

print_r(json_decode(file_get_contents('php://input')));


来源:https://stackoverflow.com/questions/5023705/type-of-application-json-prevents-post-variables-from-being-sent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!