2013-06-26 164 views
3

好吧,我希望我的用戶能夠下載一個.txt文件及其用戶名。按鈕下載.txt文件(PHP和HTML)

我已經檢查到處,到目前爲止我找不到我想要的或者甚至可能。

爲了給你什麼,我試圖做一個例子,這裏是我的代碼:

<button type="button">Download All Your Keys On A .txt 
<?php 
$file = 'logs/$session->username.txt'; 

if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist."); 

$type = filetype($file); // Get a date and timestamp $today = date("F j, Y, g:i a"); $time = time(); // Send file headers header("Content-type: $type"); header("Content-Disposition: attachment;filename=$filename"); 
header("Content-Transfer-Encoding: binary"); 
header('Pragma: no-cache'); 
header('Expires: 0'); // Send the file contents. 
set_time_limit(0); 
readfile($file); 
?> 
</button> 

我試圖讓這個當你按一下按鈕,它強制下載是的。 txt文件配置有:

$file = 'logs/$session->username.txt'; 

對不起,如果這是令人困惑和凌亂,但沒有其他方式來表示這一點。

在此先感謝!

+2

1,按鈕不能像這樣工作。您必須向您的頁面發送請求以執行下載。 2,沒有什麼應該出現在'header()' – Raptor

+3

你'$ file ='logs/$ session-> username.txt';'不會展開,因爲它裏面有單引號 – DevZer0

+0

@DevZer0也應該有一些花括號 –

回答

9

你爲什麼不有一個單獨的文件中的代碼,說download.php

<?php 
    $file = "logs/{$session->username}.txt"; 

    if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist."); 

    $type = filetype($file); 
    // Get a date and timestamp 
    $today = date("F j, Y, g:i a"); 
    $time = time(); 
    // Send file headers 
    header("Content-type: $type"); 
    header("Content-Disposition: attachment;filename={$session->username}.txt"); 
    header("Content-Transfer-Encoding: binary"); 
    header('Pragma: no-cache'); 
    header('Expires: 0'); 
    // Send the file contents. 
    set_time_limit(0); 
    readfile($file); 
?> 

請注意,您必須將報價改爲雙引號,因爲你使用' S的內部變量。因此,擴大變量,改變第一行:

$file = "logs/{$session->username}.txt"; 

在這裏,我認爲,$session->username,作爲變量您要參考。

而且有這個在HTML:

<button type="button" onclick="location.href='download.php'">Download All Your Keys On A .txt</button> 

當你點擊這個按鈕,它重定向到download.php,發起一個下載TXT文件。就如此容易。但是這需要你有兩個文件。我不明白在這裏需要按鈕。爲什麼不只是使用這樣的簡單鏈接?

<a href="download.php">Download All Your Keys On A .txt</a> 

如果你需要,你可以使用CSS來設計它。

+2

@JanDvorak說真的,*爲什麼我這麼遲鈍?*謝謝,更新了答案! :) –

+0

爲什麼不使用一個普通的鏈接,而不是一個JavaScript按鈕? –

+0

@JanDvorak建議添加。 :D –