How to upload a file with PHP, curl and HTTP POST by streaming the file?

烂漫一生 提交于 2020-02-02 10:14:05

问题


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



来源:https://stackoverflow.com/questions/5260985/how-to-upload-a-file-with-php-curl-and-http-post-by-streaming-the-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!