php下载文件实现
实现PHP文件下载的方法
使用PHP实现文件下载功能可以通过设置HTTP头信息来控制文件的下载行为。以下是一种常见的实现方式:

$file_path = '/path/to/your/file.ext'; // 文件路径
$file_name = 'downloaded_file.ext'; // 下载时显示的文件名
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.ext';
$file_name = 'large_file.ext';
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));
$chunk_size = 1024 * 1024; // 1MB chunks
$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']; // 假设通过URL参数获取文件名
// 清理文件名,防止目录遍历
$file_path = realpath($base_dir . basename($requested_file));
// 检查文件是否在安全目录内
if (strpos($file_path, $base_dir) === 0 && file_exists($file_path)) {
// 安全的下载代码
} else {
die('无效的文件请求');
}
强制下载特定文件类型
如果需要强制下载特定类型的文件(如PDF),可以修改Content-Type头:
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="document.pdf"');
以上方法提供了PHP实现文件下载的基本方案,可以根据实际需求进行调整和扩展。






