简体   繁体   中英

How to send a PHP cURL POST request to a URL, receive a file and give to the user download?

There's a url that when I pass some POST parameters it gives me back a file to download. What's the best way to make my server download that file and, while it downloads it sends to the user?

Thanks in advance

I'd use cURL for the whole thing.

I don't have a reference on me at the moment, but at least with multi-cURL, it is possible to have a callback function that is fired when a chunk of data comes in. When that happens, you echo the data out to your client.

It depends on what you want to do with the response, but the easiest way is just to set CURLOPT_RETURNTRANSFER and output the response:

$ch = curl_init("http://stackoverflow.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$resp = curl_exec($ch);
curl_close($ch);

echo $resp;

Don't forget that curl_exec returns FALSE on failure, so you probably should check that too:

if ($resp === false) die('Unable to contact server');

If you want to save the response on the server as well (instead of the above method which is just basically a dumb proxy), you could make use of CURLOPT_WRITEFUNCTION instead.

$fp = fopen('my_file', 'w');
$ch = curl_init("http://stackoverflow.com/");
curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'writefunc');
curl_exec($ch);
curl_close($ch);
fclose($fp);

function writefunc($ch, $data) {
    global $fp;
    echo $data;
    return fwrite($fp, $data);
}

The write function takes two arguments (curl handle, data), and requires a return value of the amount of data written (in our case also the amount outputted).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM