php 实现下载功能
使用 header 函数强制下载
在 PHP 中,可以通过设置 HTTP 头信息强制浏览器下载文件而不是直接打开。关键头信息包括 Content-Type、Content-Disposition 和 Content-Length。
$file_path = '/path/to/file.pdf';
$file_name = basename($file_path);
$file_size = filesize($file_path);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file_name . '"');
header('Content-Length: ' . $file_size);
readfile($file_path);
exit;
处理大文件分块下载
对于大文件,可以使用分块读取方式避免内存问题。通过设置 Content-Range 头实现断点续传功能。

$file_path = '/path/to/large_file.iso';
$chunk_size = 1024 * 1024; // 1MB chunks
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
生成动态内容下载
可以直接输出动态生成的内容作为下载文件。常见场景如导出 CSV 或 Excel 数据。

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
$data = [['Name', 'Email'], ['John', 'john@example.com']];
$output = fopen('php://output', 'w');
foreach ($data as $row) {
fputcsv($output, $row);
}
fclose($output);
安全下载控制
实现安全下载需要验证文件路径,防止目录遍历攻击。使用 realpath 确保文件在指定目录内。
$base_dir = '/safe/download/directory/';
$requested_file = $_GET['file'];
$file_path = realpath($base_dir . $requested_file);
if ($file_path && strpos($file_path, $base_dir) === 0 && is_file($file_path)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
readfile($file_path);
} else {
header('HTTP/1.0 404 Not Found');
echo 'File not found';
}
进度显示和限速控制
通过控制输出速度和计算已传输字节数,可以实现下载进度显示和限速功能。
$speed = 1024 * 50; // 50KB/s
$file_path = '/path/to/file.zip';
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
$buffer = fread($handle, $speed);
echo $buffer;
ob_flush();
flush();
sleep(1);
}
fclose($handle);






