PHP:为什么我无法下载扩展名为“rar”的文件?

时间:2013-06-28 03:33:49

标签: php download

我写了这个用于下载文件的小脚本。它与"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"个文件时,它下载了一个内容为Rar!的PHP文件,后面有两个方块。并且,此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;
 }

}

如果我回显此功能的结果,我什么也得不到。

0 个答案:

没有答案