2012-01-19 48 views
4

我正在製作一個PHP腳本,它將下載一個給定名稱和版本的文件。該文件將被存儲在服務器上是這樣的:使用PHP下載重命名的文件

/dl/Project1/1.0.txt 
/dl/Project1/1.1.txt 
/dl/Project2/2.3.jar 
/dl/Project2/2.3.1.jar 

而且路徑檢索這些文件應該是這樣的:其實下載文件時

download.php?name=Project1&type=txt&version=1.0 
download.php?name=Project1&type=txt&version=1.1 
download.php?name=Project2&type=jar&version=2.3 
download.php?name=Project2&type=jar&version=2.3.1 

的問題就出現了。在本例中,我希望前兩個文件都以Project1.txt的形式下載,並且我希望最後兩個文件的下載爲Project2.jar。我怎樣才能暫時重命名這些工作?

回答

6

發出定義文件名稱的標題。

$filename = $name . "." . $type; 
header('Content-Description: File Transfer'); 
header('Content-Type: application/octet-stream'); 
header('Content-Disposition: attachment; filename=' . $filename); 
header('Content-Transfer-Encoding: binary'); 
header('Expires: 0'); 
header('Cache-Control: must-revalidate'); 
header('Pragma: public'); 
header('Content-Length: ' . filesize($file)); 

我已經包含了額外的標題,因爲您也應該發送這些標題。這僅僅是你可以修改的例子see in the PHP documentation on readfile

0

你可能想簡單地使用內容處置標題:

header('Content-disposition: attachment; filename=Project1.txt'); 
readfile('Project1/1.0.txt'); 
2

你不需要重新命名它,你只需要在標題中更改名稱,還有就是劇本:

<?php 
// Check is set all params 
if (isset($_GET['name'], $_GET['type'], $_GET['version'])) { 
    // Get the params into variables. 

    // Secure replace to avoid the user downloading anyfile like @Kristian Antonsen said. 
    // Replace all '..' to a single '.'; 
    $name = preg_replace('/[\.]{2,}/', '.', trim($_GET['name'])); 
    // Replace any strange characters. 
    $type = preg_replace('/[^A-Za-z0-9]/', '', trim($_GET['type'])); 
    // Replace any letter and strange character. 
    $version = preg_replace('/[^0-9\.]/', '', trim($_GET['version'])); 

    /** 
    * Check is all the params filled with text 
    * and check if the version is in the right format. 
    */ 
    if (!empty($name) && 
     !empty($type) && 
     !empty($version) && 
     preg_match('/^[0-9](\.[0-9])+$', $version)) { 
    /** 
    * Get the file path, here we use 'dirname' to get the absolute path 
    * if the download.php is on root 
    */ 
    $filePath = dirname(__FILE__) . '/dl/' . $name . '/' . $version . '.' . $type; 

    // Check if the file exist. 
    if (file_exists($filePath)) { 
     // Add headers 
     header('Cache-Control: public'); 
     header('Content-Description: File Transfer'); 
     header('Content-Disposition: attachment; filename=' . $name . '.' . $type); 
     header('Content-Length: ' . filesize($filePath)); 
     // Read file 
     readfile($filePath); 
    } else { 
     die('File does not exist'); 
    } 
    } else { 
    die('Missing params'); 
    } 
} 
+0

你是對的,有一個錯誤,將允許用戶下載任何文件...我現在要編輯它。 –

+0

已編輯。我添加了一些'preg_replace'來替換在這個地方沒有意義的字符,並在獲取文件之前添加了'preg_match'檢查。 –

+0

是的,你現在就解決了。一般的解決方案是拒絕任何人試圖使用'..'來訪問任何東西,因爲他們顯然有不好的意圖,因此不需要爲他們提供任何幫助。 – kba