php下载文件实现
PHP 下载文件实现方法
使用 header() 函数强制下载
设置合适的 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));
flush();
readfile($file_path);
exit;
分块下载大文件
对于大文件,可采用分块读取方式减少内存消耗。

$chunk_size = 1024 * 1024; // 1MB per chunk
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
flush();
}
fclose($handle);
动态生成内容下载
直接将字符串内容作为文件下载,无需物理文件。
$content = "This will be downloaded as text file";
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename="data.txt"');
echo $content;
安全注意事项
- 验证文件路径防止目录遍历攻击
- 限制可下载文件类型
- 对用户输入进行严格过滤
$allowed_path = '/safe/directory/';
$requested_file = $_GET['file'];
if (strpos(realpath($requested_file), $allowed_path) !== 0) {
die('Invalid file path');
}
进度显示实现
结合 JavaScript 可创建进度条显示。

// PHP 部分
header('Content-Length: ' . filesize($file_path));
// JavaScript 部分
/*
xhr.onprogress = function(e) {
if (e.lengthComputable) {
var percent = (e.loaded / e.total) * 100;
progressBar.style.width = percent + '%';
}
};
*/
常见 MIME 类型对照
根据文件类型设置正确的 Content-Type:
- PDF:
application/pdf - ZIP:
application/zip - JPEG:
image/jpeg - Excel:
application/vnd.ms-excel - Word:
application/msword
断点续传支持
实现 Range 请求支持:
if (isset($_SERVER['HTTP_RANGE'])) {
// 解析Range头并实现部分内容发送
header('HTTP/1.1 206 Partial Content');
header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size);
}






