php文件下载问题?

时间:2014-12-07 10:22:05

标签: php

目前我正在使用以下php代码下载文件。

Php代码:

<?php
timeout();
//require_once("config.php");
if(!isset($_SESSION['front_username']) && isset($_SESSION['front_username']) == "" &&
    !isset($_SESSION['front_password']) && isset($_SESSION['front_password']) == "" &&
    !isset($_SESSION['user_id']) && isset($_SESSION['user_id']) == "") {
    header("Location:login.php");   
    exit();
}
$file_get = $_GET['filename'];  
$tmp = explode(".",$file_get);  
$file_name1 = substr($file_get, 33);    
switch ($tmp[count($tmp)-1]) {
    case "pdf": $ctype="application/pdf"; break;
    case "exe": $ctype="application/octet-stream"; break;
    case "zip": $ctype="application/zip"; break;
    case "docx":
    case "doc": $ctype="application/msword"; break;
    case "csv":
    case "xls":
    case "xlsx": $ctype="application/vnd.ms-excel"; break;
    case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
    case "gif": $ctype="image/gif"; break;
    case "png": $ctype="image/png"; break;
    case "jpeg":
    case "jpg": $ctype="image/jpg"; break;
    case "tif":
    case "tiff": $ctype="image/tiff"; break;
    case "psd": $ctype="image/psd"; break;
    case "bmp": $ctype="image/bmp"; break;
    case "ico": $ctype="image/vnd.microsoft.icon"; break;
    default: $ctype="application/force-download";
}   
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".$file_name1."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize("upload_doc/$file_get"));
ob_clean();
flush();
readfile("upload_doc/$file_get" );
?>

如果上传的文件名是字母数字,则会正确下载。但是,如果上传的文件名包含此文本,例如my doc #2.docdev & developer.doc,那么它正在下载但未显示。在我下载的文件夹中,我看到my doc

我不明白我的代码中有什么问题,有人可以告诉我吗?

1 个答案:

答案 0 :(得分:0)

&安培;和#是URL特殊字符。

尝试访问文件时,应使用urlencode PHP方法以正确的方式编码任何特殊字符: http://php.net/manual/en/function.urlencode.php

为了安全起见,您可能应该在Apache级别管理mime类型: Apache2 server mime types

或者,如果您不能,请过滤您的获取参数,以避免用户在您的服务器上请求任何路径: http://php.net/manual/en/function.filter-input.php