php 实现下载
实现 PHP 文件下载功能
PHP 可以通过设置 HTTP 头信息实现文件下载功能。以下是一个基本的实现方法:
<?php
$file_path = 'path/to/your/file.ext'; // 文件路径
$file_name = 'download_name.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 '文件不存在';
}
?>
处理大文件下载
对于大文件下载,可以使用分块读取的方式避免内存问题:
<?php
$file_path = 'large_file.zip';
$chunk_size = 1024 * 1024; // 1MB chunks
if (file_exists($file_path)) {
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;
}
?>
安全下载注意事项
确保下载文件的安全性,避免目录遍历攻击:
<?php
$allowed_dir = '/safe/download/directory/';
$requested_file = $_GET['file'];
// 验证文件路径是否在允许目录中
$real_path = realpath($allowed_dir . $requested_file);
if (strpos($real_path, $allowed_dir) !== 0) {
die('非法文件请求');
}
if (file_exists($real_path)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($real_path) . '"');
readfile($real_path);
exit;
}
?>
强制下载而非打开
某些文件类型可能会被浏览器直接打开而非下载,可以强制下载:
<?php
$file = 'document.pdf';
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="' . $file . '"');
readfile($file);
?>
进度显示
对于超大文件,可以添加下载进度显示:

<?php
$file = 'huge_file.iso';
$size = filesize($file);
header('Content-Length: ' . $size);
$handle = fopen($file, 'rb');
while (!feof($handle)) {
echo fread($handle, 8192);
ob_flush();
flush();
// 这里可以添加进度计算逻辑
$sent = ftell($handle);
$percent = ($sent / $size) * 100;
// 记录或显示进度
}
fclose($handle);
?>
这些方法提供了从基本到高级的PHP文件下载实现方案,可以根据实际需求选择适合的方式。






