1

我编写了这个用于下载文件的小 PHP 脚本。它可以正常处理"zip"文件,但无法下载"rar"文件。

这是脚本:

$file_path = $_SERVER['DOCUMENT_ROOT'].'/'.'ps-friend-redesigned'.'/' .$RESULT_ARRAY['bd_brushfilepath'];


function download_file($file, $name, $mime_type='')
{
 if(!is_readable($file)) die('File not found.');

 $size = filesize($file);
 $name = rawurldecode($name);

 $known_mime_types=array(
"pdf" => "application/pdf",
"txt" => "text/plain",
"html" => "text/html",
"htm" => "text/html",
"exe" => "application/octet-stream",
"zip" => "application/zip",
"doc" => "application/msword",
"xls" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"gif" => "image/gif",
"png" => "image/png",
"jpeg"=> "image/jpg",
"jpg" =>  "image/jpg",
"php" => "text/plain",
"rar" => "application/x-rar-compressed"
 );

 if($mime_type==''){
 $file_extension = strtolower(substr(strrchr($file,"."),1));
 if(array_key_exists($file_extension, $known_mime_types)){
    $mime_type=$known_mime_types[$file_extension];
 } else{
     $mime_type="application/force-download";
 };
 };

 @ob_end_clean(); 

 if(ini_get('zlib.output_compression'))
 ini_set('zlib.output_compression', 'Off');

 header('Content-Type: ' . $mime_type);
 header('Content-Disposition: attachment; file="'.$name.'"');
 header("Content-Transfer-Encoding: binary");
 header('Accept-Ranges: bytes');
 header("Cache-control: private");
 header('Pragma: private');
 readfile($file); 
}

现在,当我尝试下载"rar"文件时,它会下载一个 PHP 文件,其内容Rar!后面有两个方块。而且,这个 PHP 文件的大小等于实际的 RAR 文件。我试图"rar" => "application/x-rar-compressed"从这个$known_mime_types数组中排除,但它仍然不起作用。我似乎根本无法弄清楚问题所在。

更新:

我尝试使用此代码获取 mime 类型(从此处的答案之一复制的代码)。

function get_mime($file) {
  if (function_exists("finfo_file")) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
    $mime = finfo_file($finfo, $file);
    finfo_close($finfo);
    return $mime;
  } else if (function_exists("mime_content_type")) {
    return mime_content_type($file);
  } else if (!stristr(ini_get("disable_functions"), "shell_exec")) {
     // http://stackoverflow.com/a/134930/1593459
    $file = escapeshellarg($file);
    $mime = shell_exec("file -bi " . $file);
return $mime;
  } else {
   return false;
 }

}

如果我回显这个函数的结果,我什么也得不到。

4

0 回答 0