简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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