How to upload a file with PHP, curl and HTTP POST

2019-05-17 01:09发布

问题:

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.

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

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

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"

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

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

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

回答1:

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

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