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

时间:2016-06-11 12:30:34

标签: php jquery curl

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

{

//给curl文件指针以便它可以写入

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

如何点击下载文件的按钮。我知道我需要创建一个在点击时执行的功能,但我不知道如何开始。如果需要它可以使用javascript或jquery  提前致谢。

1 个答案:

答案 0 :(得分:0)

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

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

因此,您的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.

?>

此脚本将确保页面加载文件无法下载,只有在单击“提交”按钮后才能下载。

相关问题