doukanmang3687 2012-07-16 02:20
浏览 280
已采纳

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

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

  • 写回答

2条回答 默认 最新

  • doulang9521 2012-07-16 03:55
    关注

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝