cURL takes long time to start download

890 views Asked by At

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

There are 1 answers

2
Marek On

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.