dongzong7467 2014-03-10 15:40
浏览 145
已采纳

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

I have a php script that downloads files from a folder off the document root. 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?

  • 写回答

1条回答 默认 最新

  • dtoq41429 2014-03-10 15:45
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀