CURL服务器脚本未获取发布值


CURL server script not getting post values

我的应用程序使用php和CURL。我使用curl-post方法将一些细节推送到服务器。我将json字符串发布到服务器。这个json字符串包含如下值"state":"jammu & Kashmir",但当我尝试在服务器中使用$_POST收集数据时,它在"state":"jammu中断,服务器没有得到完整的json字符串。我该如何解决这个问题。我应该使用哪个函数。我应该在客户端使用urlencode,在服务器端使用urldecode吗。

function index()
    {
        $ch = curl_init();
        $post = array('id'=>'11','name'=>'jammu & kashmir','active'=>4);
        $post = json_encode($post);
        $formatorder        =   "string=".$post;
        curl_setopt($ch, CURLOPT_POSTFIELDS, $formatorder);
        curl_setopt($ch, CURLOPT_URL, "http://localhost/rest/index.php/api/example/user"); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($ch, CURLOPT_POST, TRUE);
        print_r(curl_error($ch));
        $output = curl_exec($ch);
        curl_close($ch);
        echo '<pre>';
        print_r($output);
    }

这听起来像是未对"与号"进行编码的问题(即,在发布数据时,"与号号"被解释并断开)。

在你的帖子中,你需要正确地转换你的和号(即%26)。

如果您正在进行客户端发布(通过jQuery、AJAX或类似的方式),请参阅:encodeURIComponent

如果您只发布一个JSON字符串,您可能应该将请求的Content-Type标头设置为application/json,然后从PHP原始输入中读取数据。$_POST仅用于表单编码的内容类型,并且期望传递正确格式的查询字符串以便构建$_POST数组。

从PHP原始输入中读取非常简单。它看起来是这样的:

// get JSON string from raw input
$json = file_get_contents('php://input');
// decode the JSON string to a usable data structure
$data = json_decode($json);

采用这种方法可以避免对数据进行url编码和构建查询字符串的需要。你目前遇到的问题是,当你发布类似的东西时

{"state":"jammu & Kashmir"}

在不使用application/json内容类型的情况下,PHP假设&是查询字符串的参数分隔符。要使用查询字符串和$_POST,您需要形成如下查询字符串:

json=[URL-encoded JSON string]

然后在CCD_ 11中得到POSTed数据。