drh96824 2016-06-11 12:30
浏览 73
已采纳

在按钮单击时使用curl下载文件

I need help to make this, It download the file on my server when refresh but I want that it should start download on button click. Here is my code

//File to save the contents to
$fp = fopen ('files2.tar', 'w+');

$url = "http://localhost/files.tar";

//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));

//give curl the file pointer so that it can write to it

curl_setopt($ch, CURLOPT_FILE, $fp);

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$data = curl_exec($ch);//get curl response

//done
curl_close($ch);

How to I make a button that download file on click. I know I need to make a function that execute on click but I don't know how to start. If need it can use javascript or jquery Thanks in advance.

  • 写回答

1条回答 默认 最新

  • duanbu4962 2016-06-11 12:52
    关注

    You can do this using several methods.

    One and most easy I think is to make a form and submit that form on click of a button. Check for data on server to know user want to download the file.

    So your HTML code should look like this:

    <form method="POST">
       <input type="submit" value="DOWNLOAD FILE" name="downloadfile"/>
    </form>
    

    Now at the top of the your PHP script you should check if user wants to download file or not. Like this:

    <?php
    
        if(isset($_POST["downloadfile"])) {
             //File to save the contents to
            $fp = fopen ('files2.tar', 'w+');
            $url = "http://localhost/files.tar";
            //Here is the file we are downloading, replace spaces with %20
            $ch = curl_init(str_replace(" ","%20",$url));
            //give curl the file pointer so that it can write to it
            curl_setopt($ch, CURLOPT_FILE, $fp);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            $data = curl_exec($ch);//get curl response
            //done
            curl_close($ch);
        }
    
    
        // Your other page Code should be here.
    
    ?>
    

    This script will make sure that on page load file won't get downloaded, it will get downloaded only after clicking Submit button.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?