cURL与PHP通过PUT传递数据

时间:2017-05-04 15:06:42

标签: php curl put

我想通过PUT方法将PHP卷曲到远程服务器。并流式传输到文件。

我的正常命令如下:

curl http://192.168.56.180:87/app -d "data=start" -X PUT 

我在SO上看到了thread

编辑:

使用Vitaly和Pedro Lobito评论我将我的代码更改为:

$out_file = "logging.log";
$fp = fopen($out_file, "w");

$ch = curl_init();
$urlserver='http://192.168.56.180:87/app';
$data = array('data=start');
$ch = curl_init($urlserver);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));

curl_exec($ch);
curl_close($ch);
fclose($fp);

但还是不行。

当我使用curl获得此响应时:

 192.168.56.154 - - [04/May/2017 17:14:55] "PUT /app HTTP/1.1" 200 -

我使用上面的php得到了这个回复:

 192.168.56.154 - - [04/May/2017 17:07:55] "PUT /app HTTP/1.1" 400 -

2 个答案:

答案 0 :(得分:3)

您正在错误地传递POST字符串

$data = array('data=start');
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));

在这种情况下,你已经构建了你的字符串,所以只需要包含它

$data = 'data=start';
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

http_build_query仅在您拥有key => value数组且需要将其转换为POST字符串时

答案 1 :(得分:2)

你为什么不直接将卷曲输出保存到文件中?即:

$out_file = "/path/to/file";
$fp = fopen($out_file, "w");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec($ch);
fclose($fp);
curl_close($ch);

注意:
当您询问有关错误的问题时,请始终包含错误日志。要启用错误报告,请在error_reporting(E_ALL); ini_set('display_errors', 1);脚本的顶部添加php