“application / json”的类型可防止发送变量

时间:2011-02-17 00:06:06

标签: php json curl http-headers

我发现如果我尝试PHP POST curl,postvars就可以了。一旦我添加内容类型的httpheader:application/json,postvars就不会再发生了。我已经将postvars作为JSON字符串和查询字符串进行了尝试。

显示一些代码:

$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 个答案:

答案 0 :(得分:5)

真正的HTTP Post,由PHP自动分解为数组必须使用name = value对进行格式化,在PHP中执行此操作的最佳方法是使用http_build_query函数。

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

有一个例子可以在PHP手册中使用curl:

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

你正在做的是'RAW'帖子,请看另一个问题:

How to post JSON to PHP with curl

获取RAW Json数据的快速代码段。

<?php

print_r(json_decode(file_get_contents('php://input')));
相关问题