Skip to content
WJunction - Webmaster Forum

Help with CURL download needed

Status
Not open for further replies.
Im trying to download a file directly to the client browser using CURL like this:

Code:
header([COLOR=#800000]'Content-Type: application/force-download'[/COLOR]);
header([COLOR=#800000]'Content-Disposition: attachment; filename="'[/COLOR].$filename.[COLOR=#800000]'"'[/COLOR]);
header([COLOR=#800000]'Content-Length: '[/COLOR].filesize[COLOR=#800000]');

$chdownload = curl_init();
curl_setopt($ch, CURLOPT_URL, $url]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
echo $data;[/COLOR]

This does work and downloads file to client browser. But with a quite a delay after its run. I noticed that when i start it runs download in the background probably saving it to some temporary file or in ram memory not sure and then when download is complete it outputs it to client browser for download.
I'm trying to avoid this unessesary delay, can anyone help me and point out what Im doing wrong here?
 

4 comments

The line
PHP:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
should not be there this will download the file to memory first.

should be something like,

PHP:
header('Content-Type: application/force-download'); 
header('Content-Disposition: attachment; filename="'.$filename.'"'); 
header('Content-Length: '.filesize');  
$chdownload = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url]);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch); 
curl_close($ch);
 
Last edited:
Try this..

PHP:
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($curlHandle, $string) {
    echo $string;
    return strlen($string);
});

curl_exec($ch);

// No need to echo here...

CURLOPT_WRITEFUNCTION

A callback accepting two parameters.
The first is the cURL resource, and the second is a
string with the data to be written. The data must be saved by
this callback. It must return the exact number of bytes written
or the transfer will be aborted with an error.
 
The line
PHP:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
should not be there this will download the file to memory first.

should be something like,

PHP:
header('Content-Type: application/force-download'); 
header('Content-Disposition: attachment; filename="'.$filename.'"'); 
header('Content-Length: '.filesize');  
$chdownload = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url]);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch); 
curl_close($ch);

thanks CURLOPT_RETURNTRANSFER was the problem, without it everything is working just fine
 
Status
Not open for further replies.

About the author

D
Active Member · Joined
339
Messages
25
Reactions
28
Points

Advertise on WJunction

Reach 1000's of webmasters, hosts & affiliates. Banner & sponsored-thread slots available.

Contact us
Back
Top Bottom