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('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.zip';
$chunk_size = 1024 * 1024; // 1MB chunks
if (file_exists($file_path)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
header('Content-Length: ' . filesize($file_path));
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
exit;
}
限制下载权限
添加权限验证确保只有授权用户可以下载文件。
session_start();
if (!isset($_SESSION['user_id'])) {
die('请先登录');
}
$allowed_files = ['file1.pdf', 'file2.zip'];
$requested_file = $_GET['file'];
if (in_array($requested_file, $allowed_files)) {
$file_path = '/secure/files/' . $requested_file;
// 继续下载逻辑
} else {
die('无权下载此文件');
}
强制下载特定MIME类型
明确指定文件类型而不是使用application/octet-stream。
$mime_types = [
'pdf' => 'application/pdf',
'jpg' => 'image/jpeg',
'zip' => 'application/zip'
];
$file_ext = pathinfo($file_path, PATHINFO_EXTENSION);
if (array_key_exists($file_ext, $mime_types)) {
header('Content-Type: ' . $mime_types[$file_ext]);
}
处理中文文件名
对包含非ASCII字符的文件名进行编码处理。
$file_name = '中文文件.pdf';
$encoded_name = rawurlencode($file_name);
header('Content-Disposition: attachment; filename*=UTF-8\'\'' . $encoded_name);






