php下载功能实现
实现PHP文件下载功能
使用PHP实现文件下载功能可以通过设置HTTP头信息来控制浏览器行为。以下是几种常见方法:
使用header()函数强制下载
$file_path = '/path/to/file.pdf';
$file_name = 'document.pdf';
if (file_exists($file_path)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
}
动态生成内容并下载
对于需要动态生成的内容(如CSV文件):

$data = "Name,Email,Phone\nJohn,john@example.com,123456789";
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="users.csv"');
echo $data;
exit;
大文件分块下载处理
处理大文件时使用分块读取:

$file = 'large_file.zip';
$chunk_size = 1024 * 1024; // 1MB chunks
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
$handle = fopen($file, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
exit;
}
安全注意事项
验证文件路径防止目录遍历攻击:
$base_dir = '/safe/download/directory/';
$requested_file = $_GET['file'];
$real_path = realpath($base_dir . $requested_file);
if ($real_path && strpos($real_path, $base_dir) === 0 && is_file($real_path)) {
// 安全的下载逻辑
} else {
die('Invalid file request');
}
进度显示实现
结合JavaScript实现进度显示:
// PHP端
header('Content-Length: '.filesize($file_path));
// JavaScript端
xhr.addEventListener('progress', function(e) {
if (e.lengthComputable) {
var percent = (e.loaded / e.total) * 100;
console.log(percent + '% downloaded');
}
});
以上方法涵盖了从简单下载到高级处理的多种场景,可根据实际需求选择适合的实现方式。






