在按钮单击时使用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.
我需要帮助才能做到这一点,它在刷新时在我的服务器上下载文件,但我希望它应该开始下载 点击按钮。 这是我的代码 p>
//文件将内容保存到
$ fp = fopen('files2.tar','w +');
$ url =“http://localhost/files.tar”;
//这是我们正在下载的文件,用%20替换空格
$ ch = curl_init(str_replace(“”,“%20”,$ url));
code> pre>
//给curl文件指针以便它可以写入它 p>
curl_setopt ($ ch,CURLOPT_FILE,$ fp);
ncurl_setopt($ ch,CURLOPT_FOLLOWLOCATION,true);
$ data = curl_exec($ ch); //得到卷曲响应
//完成
curl_close ($ ch);
code> pre>
如何创建一个单击下载文件的按钮。 我知道我需要创建一个单击执行的函数,但我不知道如何开始。 如果需要它可以使用javascript或jquery
提前谢谢。 p>
div>
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.