php实现下载
PHP实现文件下载的方法
使用PHP实现文件下载功能可以通过多种方式完成,以下是几种常见的方法:
使用header()函数强制下载
通过设置HTTP头信息,可以强制浏览器下载文件而不是直接打开。

$file = 'path/to/file.pdf';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
使用readfile()函数
readfile()函数可以高效地读取文件内容并输出到浏览器。
$filename = 'example.zip';
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
readfile($filename);
处理大文件下载
对于大文件,可以使用分块读取的方式,避免内存问题。

$file = 'large_file.iso';
$chunk_size = 1024*1024; // 1MB chunks
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: '.filesize($file));
$handle = fopen($file, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
安全下载注意事项
确保文件路径安全,防止目录遍历攻击。
$requested_file = basename($_GET['file']);
$file_path = 'downloads/' . $requested_file;
if (!file_exists($file_path)) {
die('File not found');
}
// 验证文件类型
$allowed_types = ['pdf', 'zip', 'doc'];
$ext = pathinfo($file_path, PATHINFO_EXTENSION);
if (!in_array($ext, $allowed_types)) {
die('Invalid file type');
}
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$requested_file.'"');
readfile($file_path);
进度显示下载
对于超大文件,可以添加下载进度显示。
function output_file($file) {
if (!file_exists($file)) return false;
$size = filesize($file);
$name = basename($file);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=$name");
header("Content-Length: $size");
$fp = fopen($file, "rb");
$sent = 0;
while ($sent < $size) {
$buffer = fread($fp, 4096);
echo $buffer;
$sent += strlen($buffer);
flush();
// 可以在这里添加进度计算逻辑
}
fclose($fp);
return true;
}
这些方法涵盖了从基本下载到高级功能的各种需求,可以根据具体场景选择适合的实现方式。





