开发者

Download remote file with curl directly

I want to download a remote file with curl and output it instantly to the user. The user should think that he downloads the file from my server instead of a remote server. I cannot buffer the whole files because some files are larger than 200 MB. Also the user would have to wait for finish buffering till he could start downloading the file.

I found a s开发者_StackOverflowcript to download a file from remote server directly:

<?php
$file_name = $_GET['file'];
$file_url = 'http://www.remote.tld/' . $file_name;
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"".$file_name."\""); 
readfile($file_url);
exit;
?>

Is this kind of a direct remote download also possible with curl?


You would need to read and output the file in chunks, as the whole 200MB file will probably not fit into your PHP script's memory.

See this question for how to do this in curl. There is a live example in the manual. Stolen and modified from that, something like this should work (untested):

<?php
curl_setopt($this->curl_handle, CURLOPT_WRITEFUNCTION, "receiveResponse");

function receiveResponse($curlHandle,$data)
   {
                        echo $data; // Ouput to the user
                        $length = strlen($data);
                        return $length;

                }
?>

Note that this is rarely a good idea. It puts relatively heavy load on the server - if you have reasonably high traffic numbers, it's a high price to pay for the vanity of being the one to serve the download. Also, of course, a 200 MB download will create 400MB on your traffic bill!


You can not serve the file from your server without buffering it on your server.

There is no technical solution, also not with CURL, since you don't have access to the DNS server of the opposite server, to hide the opposite URL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜