php实现下

以下是PHP实现文件下载功能的几种常见方法:
通过header直接输出文件
$file = 'path/to/file.pdf';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
分块下载大文件
$file = 'path/to/large_file.zip';
$chunk_size = 1024 * 1024; // 1MB chunks
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
$handle = fopen($file, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
exit;
强制下载非文件内容
$content = "This will be downloaded as file.txt";
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="file.txt"');
header('Content-Length: ' . strlen($content));
echo $content;
exit;
带权限检查的下载
$file = 'path/to/protected_file.docx';
if (user_has_permission()) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
readfile($file);
} else {
header('HTTP/1.0 403 Forbidden');
echo 'Access denied';
}
exit;
注意事项:
- 确保在发送header前没有输出任何内容
- 大文件下载建议使用分块方式避免内存问题
- 下载完成后务必使用exit或die终止脚本执行
- 真实文件名可通过basename()函数获取
- 对于敏感文件应添加权限验证







