2012-01-19 44 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