dongtanliefang8765 2011-03-29 15:48
浏览 61
已采纳

如何使用PHP发送带有文件和数据数组的PUT请求

I've set up a REST service and client in PHP and I'm having a bit of trouble with PUT.

Here's my situation: I'm coding a REST resource that should accept an array of data and an image. The REST resource should update an existing record, so I'm using PUT. I'm sending the data with a PHP curl client I wrote. So - pretty much the same situation as if you were sending a HTML multipart form to a PHP script that does a file upload and accepts some additional POST fields - except with PUT and PHP curl..

Up 'till now I've been sending the PUT request something like this (pseudo code):

$a_some_data = array('name' => 'test', 'user_id' => 4);
$body = http_build_query($a_data);

$fh = fopen('php://memory', 'rw');
fwrite($body);
rewind($fh);

$ch = curl_init();
curl_setopt_array($ch, array(
  CURLOPT_URL => 'http://myapi/resource/someid',
  CURLOPT_PUT => TRUE,
  CURLOPT_INFILE => $fh,
  CURLOPT_INFILESIZE => strlen($body)
  ));
curl_exec($ch);

and reading the data on the server like so:

parse_str(file_get_contents('php://input'), $put_data);

..which works just fine.

So now I would like to add a (binary) file into the mix. - How would I implement this on the client side? - How would I deal with the file on the server?

For a test I set up a HTML form with a file input, copied the raw multipart/form-data request it sends, and tried sending that data as a file with curl in a PUT request. That kind of works, but I would have to parse the raw data on the server manually, which I'm not sure is the best idea. Alternatively, I guess I could send the file as the body of the PUT request, and add the other parameters in the URL as a query string - but I guess that kind of defies the point of a PUT REST resource..

Please share your thoughts on this. Thanks!

  • 写回答

1条回答 默认 最新

  • dongmi1663 2011-03-29 17:50
    关注

    There are at least two other ways unless your original version isn't enough (since libcurl should deal just fine with binary files too with that script). Note that how you decide receive the PUT in the receiving end is not a curl issue so I'll leave it out of this response.

    1 - Like you started out, but provide a CURLOPT_READFUNCTION with which you feed the data to libcurl that it will send.

    2 - Use CURLOPT_POSTFIELDS (with a string) and make it look like a POST, and then you change the HTTP method with CURLOPT_CUSTOMREQUEST to "PUT"

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog