简体   繁体   English

单击按钮使用curl下载文件

[英]Download file using curl on button click

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. 如果需要,可以使用javascript或jquery预先感谢。

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: 因此,您的HTML代码应如下所示:

<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. 现在,在您的PHP脚本的顶部,您应该检查用户是否要下载文件。 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. 该脚本将确保不会下载页面加载文件,仅在单击“提交”按钮后才会下载该文件。

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

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