php下载实现
PHP 文件下载实现方法
直接输出文件内容 通过设置 HTTP 头信息并直接输出文件内容实现下载功能。需要指定正确的 Content-Type 和 Content-Disposition。
$file = 'path/to/file.pdf';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
分块下载大文件 对于大文件下载,可以使用分块读取方式避免内存问题。
$file = 'large_file.zip';
$chunk_size = 1024*1024; // 1MB chunks
$handle = fopen($file, 'rb');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
exit;
安全下载控制 添加权限验证和日志记录等安全措施。
session_start();
if (!isset($_SESSION['user_id'])) {
die('Access denied');
}
$safe_dir = '/var/www/downloads/';
$requested_file = basename($_GET['file']);
$full_path = $safe_dir . $requested_file;
if (!file_exists($full_path)) {
die('File not found');
}
// 记录下载日志
file_put_contents('download.log', date('Y-m-d H:i:s').' '.$_SESSION['user_id'].' '.$requested_file.PHP_EOL, FILE_APPEND);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$requested_file.'"');
readfile($full_path);
强制下载特定类型 确保某些文件类型总是触发下载而非在浏览器中打开。
$file = 'document.pdf';
$mime_types = [
'pdf' => 'application/pdf',
'zip' => 'application/zip'
];
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
$content_type = $mime_types[$ext] ?? 'application/octet-stream';
header('Content-Type: '.$content_type);
header('Content-Disposition: attachment; filename="'.basename($file).'"');
readfile($file);
处理中文文件名 正确处理包含非ASCII字符的文件名下载。

$file = '中文文件.txt';
$encoded_name = rawurlencode($file);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename*=UTF-8\'\''.$encoded_name);
readfile($file);
实现文件下载功能时需要注意文件路径安全、内存使用优化和特殊字符处理等问题。根据具体需求选择合适的实现方式,并确保添加适当的安全验证措施。






