简体   繁体   English

PHP CURL 值为空的 POST 数据

[英]PHP CURL POST data with value empty

I have this code to POST data to an url that is receiving the data with below, with content-type header set as text/html我有这个代码将数据发布到 url 正在接收下面的数据,内容类型 header 设置为 text/html

file_get_contents("php://input");

This is the code That I used to POST to url and it is sending the data, but without values (i'm sending an array data with key values).这是我用来 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);

However, it's sending the data, but without the values, since I get a response back from the url saying that values are empty.但是,它正在发送数据,但没有值,因为我从 url 收到回复说值是空的。

Moreover, I checked the curl_errno($ch) and it doesn't return anything so there is no error within my code (I think?)此外,我检查了 curl_errno($ch) 并且它没有返回任何内容,所以我的代码中没有错误(我认为?)

Can someone help me out?!有人可以帮我吗?!

Thanks in advance!提前致谢!

OK I solved the problem and it was pretty simple.好的,我解决了这个问题,这很简单。

Just swap the http_build_query with json_encode, and make sure to only set the curl_setopt as it is.只需将 http_build_query 与 json_encode 交换,并确保仅按原样设置 curl_setopt。

add the bottom code also.还添加底部代码。

curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

I don't know why but for some reason, if I add other curl_setopt variables like我不知道为什么,但出于某种原因,如果我添加其他 curl_setopt 变量,例如

curl_setopt($ch, CURLOPT_POST, true);

it does not work.这是行不通的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM