0

我有一个关于制作下载系统的问题。我过去做过一个,但它非常基本。我所做的是将下载的文件名添加到数据库中:

id | title     | filename
---|-----------|--------------
 1 | Something | something.zip

然后,当用户访问 download.php?id=1 时,他将被简单地重定向到:/path/to/downloads/something.zip,使用:

header('Location: /path/to/downloads/something.zip');

这会导致浏览器自动开始下载。但是这样做可以吗?我正在使用 Codeigniter 构建一个下载系统,并且有一个下载助手可用。要提供下载,我需要:

$data = file_get_contents('/path/to/downloads/something.zip');
$name = 'Something';

force_download($name, $data);

我注意到,由于 file_get_contents(),与简单的重定向相比,这种方式的下载速度较慢。我有一些大型下载(最大 1 GB)。你有什么建议?我应该使用 Codeigniter 下载帮助程序,直接使用重定向到文件还是其他方式?

4

1 回答 1

1

取自php.net

function downloadFile( $fullPath ){ 

// Must be fresh start 
if( headers_sent() ) 
die('Headers Sent'); 

// Required for some browsers 
if(ini_get('zlib.output_compression')) 
ini_set('zlib.output_compression', 'Off'); 

// File Exists? 
if( file_exists($fullPath) ){ 

// Parse Info / Get Extension 
$fsize = filesize($fullPath); 
$path_parts = pathinfo($fullPath); 
$ext = strtolower($path_parts["extension"]); 

// Determine Content Type 
switch ($ext) { 
   case "pdf": $ctype="application/pdf"; break; 
   case "exe": $ctype="application/octet-stream"; break; 
   case "zip": $ctype="application/zip"; break; 
   case "doc": $ctype="application/msword"; break; 
   case "xls": $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; 
   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=\"".basename($fullPath)."\";" ); 
header("Content-Transfer-Encoding: binary"); 
header("Content-Length: ".$fsize); 
ob_clean(); 
flush(); 
readfile( $fullPath ); 

} else die('File Not Found'); 

} 
于 2012-07-12T12:48:36.017 回答