cURL takes long time to start download

吃可爱长大的小学妹 提交于 2019-12-14 03:57:21

问题


I'am trying to download a file (1GB) on server C via server B, which has the code:

header("Content-Disposition: attachment; filename=How to Use Git and GitHub Videos.zip");
header("Content-type: application/octet-stream");
header("Content-Transfer-Encoding: binary");

$url = "http://zips.udacity-data.com/ud775/How%20to%20Use%20Git%20and%20GitHub%20Videos.zip";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 256);

curl_exec ($ch);
curl_close($ch);

I was expecting it will momentally start dwonlaoding a file. But instead I have to wait so long time till my browser window will ask where to save it. I thought curl_setopt($ch, CURLOPT_BUFFERSIZE, 256); means that it will transfer the file chunk by chunk so i don'thave to wait it will read the all file first.

So why it takes so long time to start download? How can I fix it? if this method is wrong please suggest me something else


回答1:


That's because curl_exec() blocks till it reads full response (consuming 1GB of memory in the process in your case). You can make it call your own function however:

curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $buffer) {
  echo $buffer;
  return strlen($buffer);
});
curl_exec ($ch); // curl will call CURLOPT_WRITEFUNCTION as it receives data inside curl_exec()

Be sure CURLOPT_RETURNTRANSFER is not set at all, neither to false, neither to true.



来源:https://stackoverflow.com/questions/30560855/curl-takes-long-time-to-start-download

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