php实现文件下载代码
实现文件下载的基本方法
使用PHP的header()函数设置HTTP头信息,结合readfile()函数实现文件下载。以下是一个基础示例:
$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('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
} else {
echo '文件不存在';
}
处理大文件下载
对于大文件下载,使用分块读取避免内存问题:

$file_path = '/path/to/large_file.zip';
$chunk_size = 1024 * 1024; // 1MB per chunk
if (file_exists($file_path)) {
$handle = fopen($file_path, '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) {
// 安全下载逻辑
} else {
die('非法文件请求');
}
支持断点续传
实现HTTP Range请求支持:
$file_path = '/path/to/resumable.file';
$file_size = filesize($file_path);
$range = isset($_SERVER['HTTP_RANGE']) ? $_SERVER['HTTP_RANGE'] : false;
if ($range) {
list($size_unit, $range_orig) = explode('=', $range, 2);
if ($size_unit == 'bytes') {
list($range, $extra_ranges) = explode(',', $range_orig, 2);
} else {
$range = '';
}
} else {
$range = '';
}
if ($range) {
// 处理范围请求
} else {
// 完整文件下载
}
常用MIME类型设置
根据文件扩展名设置正确的Content-Type:
$mime_types = [
'pdf' => 'application/pdf',
'txt' => 'text/plain',
'jpg' => 'image/jpeg',
'png' => 'image/png',
'zip' => 'application/zip'
];
$ext = strtolower(pathinfo($file_path, PATHINFO_EXTENSION));
if (isset($mime_types[$ext])) {
header('Content-Type: ' . $mime_types[$ext]);
} else {
header('Content-Type: application/octet-stream');
}






