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

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

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样