单个文件
if (is_file($file)) { // 判断是否文件 bool
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=" . $file);
readfile($file);
}
多个文件
ZipArchive类
public static function PackDown($file_arr, $download_name='zip')
{
// 临时保存zip
$temp_zip = 'tmp.zip';
$zip = new \ZipArchive();
$zip->open($temp_zip, \ZipArchive::OVERWRITE | \ZipArchive::CREATE);
foreach ($file_arr as $file_path) {
$content = file_get_contents($file_path);
if ($content) {
$file_name = explode('/', $file_path);
$file_name = end($file_name); // 提取文件名
$zip->addFromString($file_name, $content); // 保存
}
unlink($file_path); // 删除文件
}
$zip->close();
// 下载zip
$zip_file = fopen($temp_zip, "r"); // 打开zip文件
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Type: application/zip"); // zip格式
header("Accept-Ranges: bytes");
header("Content-Transfer-Encoding: binary"); // 二进制文件
header("Accept-Length: " . filesize($temp_zip) ?: 1);
header("Content-Disposition: attachment; filename={$download_name}.zip");
$buffer = filesize($temp_zip) ?: 1;
while (!feof($zip_file)) {
// 将文件读入内存
$file_data = fread($zip_file, $buffer);
// 每次向客户端回送1024个字节的数据
echo $file_data;
}
fclose($zip_file); // 关闭zip文件
unlink($temp_zip); // 删除zip文件
}