php实现下载功能
PHP 实现下载功能的方法
直接文件下载
通过设置 HTTP 头部强制浏览器下载文件而非直接打开:
$file_path = '/path/to/file.pdf';
$file_name = 'document.pdf';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file_name) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
动态生成内容下载
适用于需要将字符串或动态生成的内容作为文件提供下载:
$content = "This will be saved in the downloaded file.";
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename="data.txt"');
echo $content;
exit;
大文件分块下载
处理大文件时避免内存溢出:
$file = 'large_video.mp4';
$chunk_size = 1024 * 1024; // 1MB per chunk
$handle = fopen($file, 'rb');
header('Content-Type: video/mp4');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
exit;
安全下载注意事项
- 验证文件路径防止目录遍历攻击:
$base_dir = '/safe/directory/'; $requested_file = $_GET['file']; $real_path = realpath($base_dir . $requested_file);
if (strpos($real_path, $base_dir) !== 0 || !file_exists($real_path)) { die('Invalid file'); }
常见 MIME 类型对照
根据文件类型自动设置正确的 Content-Type:
```php
$mime_types = [
'txt' => 'text/plain',
'pdf' => 'application/pdf',
'jpg' => 'image/jpeg',
'png' => 'image/png'
];
$ext = strtolower(pathinfo($file_path, PATHINFO_EXTENSION));
header('Content-Type: ' . ($mime_types[$ext] ?? 'application/octet-stream'));
断点续传支持
实现 HTTP 范围请求(Range Requests):

if (isset($_SERVER['HTTP_RANGE'])) {
$size = filesize($file_path);
list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
list($start, $end) = explode('-', $range, 2);
$start = max(0, (int)$start);
$end = min($size - 1, empty($end) ? ($size - 1) : (int)$end);
header('HTTP/1.1 206 Partial Content');
header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size);
header('Content-Length: ' . ($end - $start + 1));
$fp = fopen($file_path, 'rb');
fseek($fp, $start);
echo fread($fp, $end - $start + 1);
fclose($fp);
}
以上方法涵盖了从基础文件下载到高级功能的实现,开发者可根据实际需求选择适合的方案。






