如何用PHP解析cURL postdata?

时间:2014-09-09 09:39:47

标签: php json parsing curl

有没有办法按cURL PHP解析帖子?

我有一个PHP客户端使用此cURL调用:

data1 = array(
    "email" => $email,
    "firstname" => $firstname,
    "lastname" => $lastname,
    "code" => $code
);
$data_string = json_encode($data1);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $user.":".$passwd);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);
$response = curl_exec($ch);

如何在服务器上解析此cURL帖子?我想访问JSON数据(CURLOPT_POSTFILEDS内容)。

它不在$ _POST或$ _GET ......任何想法?

3 个答案:

答案 0 :(得分:1)

标准输入可用:

$data = file_get_contents('php://stdin');
您在请求中发送的

Content-Type标头使PHP不解析POST正文并以此方式使其可用。因此,如果您将来想知道它为什么会丢失,请检查您的标题请求。

答案 1 :(得分:0)

这是我将卷曲数据发布到我的服务器的方式:

    curl_setopt($ch, CURLOPT_URL, $this->_config['listener_file'] );
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "data=".$data_enc."");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$ data_enc是一个json字符串;

这是我阅读数据的方式:

$_POST['data']

答案 2 :(得分:-1)

我不认为POST字段会被发送,除非curl请求有:

curl_setopt($ch, CURLOPT_POST, 1);

编辑: 并使用http_build_query而不是json_encode。 post参数不是JSON编码的。