当前位置:首页 > PHP

php下载文件实现

2026-02-27 14:53:46PHP

PHP 实现文件下载

在 PHP 中实现文件下载功能通常涉及设置正确的 HTTP 头信息并输出文件内容。以下是几种常见的实现方式:

使用 readfile() 函数

$file_path = 'path/to/your/file.pdf';
$file_name = basename($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;

使用 fread() 逐块读取大文件

对于大文件,可以分块读取以避免内存问题:

$file_path = 'path/to/large/file.zip';
$file_name = basename($file_path);
$chunk_size = 1024 * 1024; // 1MB chunks

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));

$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
    echo fread($handle, $chunk_size);
    ob_flush();
    flush();
}
fclose($handle);
exit;

实现安全下载

为防止目录遍历攻击,应验证文件路径:

$base_dir = '/safe/download/directory/';
$requested_file = $_GET['file'] ?? '';
$file_path = realpath($base_dir . $requested_file);

// 验证文件是否在允许的目录中
if ($file_path && strpos($file_path, realpath($base_dir)) === 0 && is_file($file_path)) {
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
    header('Content-Length: ' . filesize($file_path));
    readfile($file_path);
} else {
    header('HTTP/1.0 404 Not Found');
    echo 'File not found';
}
exit;

强制下载特定 MIME 类型

可以强制浏览器下载而不是显示某些文件类型:

$file_path = 'path/to/file.html';
$file_name = basename($file_path);

header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="'.$file_name.'"');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;

注意事项

  • 确保脚本在输出文件内容前没有输出任何其他内容(包括空格和换行符)
  • 对于大文件下载,考虑增加 PHP 执行时间限制:set_time_limit(0)
  • 在生产环境中应添加适当的权限检查和日志记录
  • 考虑使用 X-Sendfile(如 Apache 的 mod_xsendfile)来提高大文件下载性能

php下载文件实现

标签: 文件php
分享给朋友:

相关文章

php实现搜索功能

php实现搜索功能

实现基础搜索功能 使用PHP和MySQL实现基础的搜索功能需要结合表单提交与数据库查询。创建一个HTML表单用于接收用户输入的搜索关键词,通过PHP处理表单数据并查询数据库。 // 搜索表单 (H…

php实现文件下载

php实现文件下载

PHP实现文件下载的方法 通过PHP实现文件下载功能,可以采用多种方式,以下是几种常见的实现方法: 使用header()函数强制下载 设置HTTP头信息,强制浏览器下载文件而非直接打开:…

git php实现

git php实现

Git 与 PHP 的集成实现 使用 PHP 执行 Git 命令 通过 PHP 的 exec()、shell_exec() 或 passthru() 函数可以直接调用 Git 命令,适用于服务器端操作…

php实现

php实现

PHP 实现的基本方法 PHP 是一种服务器端脚本语言,广泛用于 Web 开发。以下是 PHP 实现的一些常见方法。 变量与数据类型 PHP 变量以 $ 开头,支持多种数据类型: $n…

php实现注册

php实现注册

注册功能实现步骤 数据库准备 创建用户表,包含字段如id、username、password、email等。示例SQL: CREATE TABLE users ( id INT AUTO_I…

java如何读取文件

java如何读取文件

读取文件的常用方法 Java提供了多种读取文件的方式,适用于不同场景和需求。以下是几种常见的方法: 使用FileInputStream和BufferedInputStream读取二进制文件 t…