2010-09-22 35 views
2

我想知道如何在PHP中爲我的下載按鈕實現邏輯。我在網絡服務器上有一個文件,並有一個頁面下載按鈕。我想在用戶按下載按鈕時開始下載文件。如何實施?謝謝如何爲我的下載按鈕實現邏輯

+4

只需使用一個簡單的鏈接,而不是一個按鈕? – halfdan 2010-09-22 19:51:01

+0

這裏的問題是我不想向用戶顯示可下載文件的路徑。如果我將使用鏈接用戶可以看到文件的URL,這是不可接受的 – 2010-09-22 19:53:40

+3

您正在從Web服務器拉取資源。該資源將始終有一個地址,您無法隱藏該地址。 – Welbog 2010-09-22 19:55:33

回答

3

下面是如何開始下載,而不讓用戶看到文件的真實路徑。將鏈接指向download.php?file = filename,並確保該文件存在於下載文件夾中。然後使用此代碼來檢查文件是否存在並讓它們下載。或者,您可以輸入登錄檢查或其他檢查。

<?php 
//download.php 
$dir = '/path/to/file/'; 
if (isset($_GET['file']) && !is_dir($_GET['file']) && file_exists($dir . $_GET['file'] . '.zip')) 
{ 
    $file = $dir . $_GET['file'] . '.zip'; 
    header('Content-type: application/force-download'); 
    header('Content-Transfer-Encoding: Binary'); 
    header('Content-length: ' . filesize($file)); 
    header('Content-disposition: attachment; filename=' . basename($file)); 
    readfile($file); 
} 
else 
{ 
    echo 'No file selected'; 
} 
?> 

此外,您還可以阻止使用.htaccess文件訪問文件夾中的文件。如果您想要,請將以下代碼放在文件目錄中的.htaccess文件中。

order allow, deny 
deny from all 
+0

這很危險。如果我決定請求'../../../ home/user/something'文件怎麼辦? 'file_exists'將匹配請求,假設文件確實存在,'readfile'將愉快地讀取'/ path/to/file /../../../ home/user/something'文件。你*可以*保證這種方法,但爲什麼要冒這個風險? – Welbog 2010-09-22 20:12:14

+0

@ Welbog:謝謝!我完全忘了那個..我已經改變了腳本,以便它只允許下載一個.zip文件。它當然可以擴展,所以它允許更多的擴展如.pdf或其他。 – Evert 2010-09-22 20:22:26

+0

這有點更好,但它仍然可以讓你從其他目錄抓取zip文件。最好不要在實際路徑中使用用戶提供的標識符。 – Welbog 2010-09-22 20:24:22

1

在這兩種設置sollutions(ReadFile的或X的sendfile報頭)的文件可以被存儲公共服務器目錄(通常稱爲htdocs中或www)。

//page.php 
<form method="get" action="download.php"> 
    With button <input type="submit" value="Download file" /> 
</form> 
or 
With link <a href="download.php">Download file</a> 


<?php // download.php 
$file = '/path/to/file.zip'; 

if (file_exists($file)) { 
    // send headers that indicate file download 
    header('Content-Description: File Transfer'); 
    header('Content-Type: application/octet-stream'); 
    header('Content-Disposition: attachment; filename='.basename($file)); 
    header('Content-Transfer-Encoding: binary'); 
    header('Content-Length: ' . filesize($file)); 
    ob_clean(); 
    flush(); 
    // send file (must read comments): http://php.net/manual/en/function.readfile.php 
    readfile($file); 
    exit; 
} 

更好sollution,如果你的服務器支持X-SENDFILE(mod_xsendfile)標題是:

<?php 
header('Content-Disposition: attachment;filename=hello.txt'); 
header('X-Sendfile: /path/to/file.zip'); 

http://codeutopia.net/blog/2009/03/06/sending-files-better-apache-mod_xsendfile-and-php/