php实现下载文件
使用PHP实现文件下载
PHP可以通过设置HTTP头信息实现文件下载功能。以下为几种常见方法:
使用readfile()函数
$file = 'path/to/file.pdf';
if (file_exists($file)) {
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;
}
使用fopen()和fread()实现大文件下载
$file = 'large_file.zip';
if (file_exists($file)) {
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, 8192);
ob_flush();
flush();
}
fclose($handle);
exit;
}
强制下载特定类型文件
$file = 'example.docx';
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
处理中文文件名
$file = '中文文件.txt';
$filename = urlencode(basename($file));
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename*=UTF-8\'\''.$filename);
readfile($file);
exit;
注意事项
- 确保文件路径正确且服务器有读取权限
- 在发送头信息前不能有任何输出
- 大文件下载建议分块读取避免内存问题
- 下载完成后使用exit终止脚本执行
- 考虑添加安全验证防止未授权下载
这些方法可以根据实际需求进行调整,如添加下载权限验证、记录下载日志等功能。







