php怎么实现下载
使用 PHP 实现文件下载
通过设置 HTTP 头信息强制浏览器下载文件而非直接打开。以下是一个基本实现方法:
$file_path = '/path/to/your/file.pdf'; // 文件路径
$file_name = 'download.pdf'; // 下载时显示的文件名
if (file_exists($file_path)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file_name . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
} else {
echo '文件不存在';
}
大文件分块下载
处理大文件时使用分块读取避免内存问题:

$file_path = '/path/to/large/file.zip';
$chunk_size = 1024 * 1024; // 1MB 分块
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
动态生成内容下载
将动态生成的内容(如 CSV 数据)直接提供下载:

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="data.csv"');
$output = fopen('php://output', 'w');
fputcsv($output, ['Name', 'Email', 'Phone']);
fputcsv($output, ['John', 'john@example.com', '123456']);
fclose($output);
安全注意事项
验证用户权限和文件路径防止任意文件下载:
$allowed_files = [
'/safe/path/file1.pdf',
'/safe/path/file2.zip'
];
$requested_file = $_GET['file'];
if (in_array($requested_file, $allowed_files)) {
// 安全下载逻辑
} else {
die('非法文件请求');
}
进度显示实现
通过输出缓冲实现下载进度显示(需客户端JavaScript配合):
ob_start();
$file_path = '/path/to/file';
$total_size = filesize($file_path);
$downloaded = 0;
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
$buffer = fread($handle, 8192);
echo $buffer;
$downloaded += strlen($buffer);
$progress = round(($downloaded / $total_size) * 100);
echo "<script>parent.updateProgress($progress)</script>";
ob_flush();
flush();
}
fclose($handle);
这些方法覆盖了从基本文件下载到高级功能的实现,可根据具体需求选择合适的方式。






