簡體   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