下载名称中带有空格的文件 - 通过htaccess限制

时间:2015-08-05 14:50:58

标签: php apache .htaccess .htpasswd

我偶然发现了保护档案的奇怪方法。

基本上,受保护文件夹中有空的download.php文件和两个导致文件下载的文件(来自同一文件夹): .htpwd存储密码和.htaccess:

RewriteEngine On
##RewriteBase /
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?example.com [NC]
RewriteRule \.(.*)$ - [NC,F,L]

RewriteCond %{QUERY_STRING} ^filename=(.*)$
RewriteRule ^download\.php$ %1
RewriteRule (.*) - [E=file:$1]
Header set Content-type "octet-stream"
Header set Content-disposition "attachment; filename=%{file}e" env=file

##AuthName "Restricted Access" 
##AuthType Basic
##AuthUserFile /local/home/example/example.com/downloads/.htpwd
##AuthGroupFile /dev/null 
##require valid-user

下载链接示例:
http://www.example.com/downloads/download.php?filename=dog%20cat%20cow.zip

如果filename是dog-cat-cow.zip - 一切正常。文件名为: “dog cat cow.zip”然后将下载文件,但下载后的文件名将是“dog”而不是“dog cat cow.zip”。所以问题是人们在没有扩展的情况下获得文件,并且不知道如何处理它。

考虑到我根本无法重命名这些文件并删除空格,如何解决这个问题?我不是如何阅读.htaccess的专家,没有我能想到的短语给出任何类似的问题解决方案。 有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如评论中所述,也许可以尝试:

RewriteEngine On
##RewriteBase /
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?example.com [NC]
RewriteRule \.(.*)$ - [NC,F,L]

RewriteCond %{QUERY_STRING} ^filename=(.*)$
RewriteRule ^download\.php$ %1
RewriteRule (.*) - [E=file:$1]
Header set Content-type "octet-stream"
Header set Content-disposition "attachment; filename='%{file}'" env=file

##AuthName "Restricted Access" 
##AuthType Basic
##AuthUserFile /local/home/example/example.com/downloads/.htpwd
##AuthGroupFile /dev/null 
##require valid-user

或者,为什么不在download.php文件中设置内容类型和处置?

$fileStorageDirectory = '/the/folder/the/downloadable/files/are/in/';

// Check for Parameter
if( !isset( $_GET['filename'] ) || $_GET['filename']=='' ){
  header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found', true, 404);
  die('No File Specified');
}

$fileName = trim( $_GET['filename'] );
$fileRequested = $fileStorageDirectory.$fileName;
// Check File Exists
if( !file_exists( $fileRequested ) ){
  header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found', true, 404);
  die('File Not Found');
}
// Check File is Readable
if( !is_readable( $fileRequested ) ){
  header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found', true, 404);
  die('File Not Accessible');
}
// Send the File
header( 'Content-Type: application/octet-stream' );
header( 'Content-Disposition: attachment; filename="'.fileName.'"' );
readfile( $fileRequested );
exit;