如何使用PHP,curl和HTTP POST通过流文件上传文件?

问题描述:

假设我有一个大文件,我想使用PHP和curl的HTTP POST到webservice。该文件大于我可以让PHP使用的内存量。

Lets say I have a large file that I want to HTTP POST to a webservice using PHP and curl. The file is larger than the amount of memory I can let PHP use.

基本上,我正在寻找一种方式直接流文件的内容到curl,没有

Basically I'm looking for a way to stream the content of a file directly to curl, without reading the entire file into memory.

我已使用multipart POSTs和PUT成功,但不是使用POST的二进制数据上传。

I have success using multipart POSTs and PUT, but not "binary data" upload with POST.

我想在PHP中实现这个命令行:

What I want to achieve in PHP is what this command line does:

 $ curl -X POST -H "Content-Type: image/jpeg" \
       --data-binary "@large.jpg" "http://example.com/myservice"

使用curl_setopt尝试了很多选项,例如INFILE,POSTFIELDS,Content-Type头,但没有运气。

Tried a lot of options with curl_setopt, such as INFILE, POSTFIELDS, Content-Type header, but no luck.

它适用于multipart虽然,但我需要一个原始的POST请求,没有multiparts:

It works with multipart though, but I need a raw POST request, no multiparts:

$post['file'] = "@large.jpg";
curl_setopt($c, CURLOPT_POSTFIELDS, $post);


PHP / CURL绑定支持CURLOPT_READFUNCTION选项

The PHP/CURL binding supports the CURLOPT_READFUNCTION option, which allows you to pass data to send chunk-by-chunk using that callback.

几乎完全相同的逻辑,如下面的C示例所示:
http://curl.haxx.se/libcurl/c/post-callback.html

Pretty much exactly the same logic as is shown in this C example: http://curl.haxx.se/libcurl/c/post-callback.html