繁体   English   中英

单击按钮使用curl下载文件

[英]Download file using curl on button click

我需要帮助,在刷新时它将下载文件下载到我的服务器上,但是我希望它应在单击按钮时开始下载。 这是我的代码

//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));

//给予文件指针卷曲,使其可以写入

curl_setopt($ch, CURLOPT_FILE, $fp);

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

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

//done
curl_close($ch);

我如何制作一个按钮,单击该按钮即可下载文件。 我知道我需要创建一个可以在单击时执行的函数,但是我不知道如何启动。 如果需要,可以使用javascript或jquery预先感谢。

您可以使用多种方法执行此操作。

我认为最简单的方法是制作一个表单,然后单击按钮提交该表单。 在服务器上检查数据,以了解用户要下载文件。

因此,您的HTML代码应如下所示:

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

现在,在您的PHP脚本的顶部,您应该检查用户是否要下载文件。 像这样:

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

?>

该脚本将确保不会下载页面加载文件,仅在单击“提交”按钮后才会下载该文件。

暂无
暂无

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

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