我有这段代码将数据发布到正在接收以下数据的网址,内容类型标头设置为text/html
file_get_contents("php://input");
这是我用来 POST 到 url 的代码,它正在发送数据,但没有值(我正在发送带有键值的数组数据)。
$url = "http://url im sending data to";
$object = array(
"key1" => "123",
"key2" => "345",
"key3" => "567"
);
$data = http_build_query($object, '', '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTREDIR, 3);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
但是,它正在发送数据,但没有值,因为我从 url 收到响应,说值是空的。
此外,我检查了curl_errno($ch),它没有返回任何内容,因此我的代码中没有错误(我认为?)
有人可以帮我吗?!
提前致谢!
好的,我解决了问题,而且非常简单。
只需将 http_build_query 与 json_encode 交换,并确保仅按原样设置curl_setopt。
还添加底部代码。
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
我不知道为什么,但出于某种原因,如果我添加其他curl_setopt变量,例如
curl_setopt($ch, CURLOPT_POST, true);
它不起作用。
如果您想进行类似于 AJAX 帖子的调用(但来自 php 文件):
$.ajax({
url: "http://url/code.php",
type: 'POST',
data: data,
dataType: "json",
success: function (result) {
//do something
}
});
您可以尝试一下这个功能:
function curlAjaxPost($url, $data)
{
$postdata = http_build_query($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
$result = curl_exec($ch);
curl_close($ch);
return $result;
}