简体   繁体   English

在PHP下载中从文件名正确转义坏字符

[英]Properly escaping bad characters from filename in a PHP download

I have a php script that downloads files from a folder off the document root. 我有一个php脚本,可以从文档根目录下的文件夹中下载文件。 Here it is: 这里是:

$getdir = $_GET['dir'];
$getdoctype = $_GET['doctype'];
$getfile = $_GET['filename'];
if ( !preg_match('/^[a-zA-Z]+[a-zA-Z0-9\s\_\-]+$/', urldecode($getdir)) ||
     !preg_match('/^[a-zA-Z]+[a-zA-Z0-9\s\_\-]+$/', urldecode($getdoctype))) {
    die('Bad parameter!');
}
$dir = "/var/www/uploads/$getdir/$getdoctype/";

$type = mime_content_type( $dir . $getfile );
if (file_exists($dir . $getfile)) {
header('Content-Type: ' . $type);
header('Content-Disposition: attachment;filename=' . $getfile);
readfile($dir . $getfile);
}
else{
echo "File Not Found";
}

The problem is alot of the time the files that are uploaded to my website have invalid characters like + # % () alot of these characters are ok locally but on the web they are interpreted as something else. 问题是很多时候上传到我的网站的文件带有无效字符,例如+#%(),这些字符很多在本地都可以,但在网络上它们被解释为其他内容。 Using my existing script how would I achieve properly escaping these characters so that my download works? 使用现有脚本,我如何正确地转义这些字符,以便下载工作?

You can get around having some special chars in the file downloads by wrapping the filename in quotes 通过将文件名用引号引起来,可以避免文件下载中包含一些特殊字符

header('Content-Disposition: attachment;filename="' . $getfile . '"');

Alternatively you could get regex to remove the special chars, although this is not the best option. 另外,您也可以使用正则表达式删除特殊字符,尽管这不是最佳选择。

something like this would do it: Regular Expression for alphanumeric and underscores 这样的事情就可以做到: 字母数字和下划线的正则表达式

To do this in regex you would use 为此,您将使用正则表达式

$filteredName = preg_replace('/[^a-z0-9\.]/i', '', $filename);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM