简体   繁体   English

如何将PHP cURL POST请求发送到URL,如何接收文件并提供给用户下载?

[英]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. 有一个网址,当我传递一些POST参数时,它会给我一个要下载的文件。 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. 我会在整个过程中使用cURL。

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. 我目前没有引用,但是至少使用multi-cURL时,有可能有一个回调函数,当有大量数据传入时会触发该回调函数。发生这种情况时,您会将数据回显到您的客户。

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: 这取决于您要对响应执行的操作,但是最简单的方法就是设置CURLOPT_RETURNTRANSFER并输出响应:

$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: 不要忘记curl_exec在失败时返回FALSE,因此您可能也应该检查一下:

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. 如果您还希望将响应保存在服务器上(而不是上面的方法基本上只是一个哑代理),则可以改用CURLOPT_WRITEFUNCTION。

$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). write函数接受两个参数(curl句柄,data),并要求返回写入的数据量(在本例中还包括输出量)的返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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