当前位置:首页 > PHP

php实现文件下载

2026-01-08 12:10:45PHP

PHP 实现文件下载的方法

使用 header() 函数强制下载

设置正确的 HTTP 头信息,强制浏览器下载文件而不是直接打开。

$file = 'path/to/file.pdf';
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}

处理大文件下载

对于大文件,可以使用分块读取的方式,避免内存问题。

php实现文件下载

$file = 'path/to/large_file.zip';
$chunk_size = 1024 * 1024; // 1MB chunks

if (file_exists($file)) {
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Content-Length: ' . filesize($file));

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

动态生成文件并下载

可以直接生成内容并作为文件下载,比如生成 CSV 文件。

php实现文件下载

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="example.csv"');

$output = fopen('php://output', 'w');
fputcsv($output, ['Name', 'Email', 'Phone']);
fputcsv($output, ['John Doe', 'john@example.com', '123456789']);
fclose($output);
exit;

安全注意事项

确保下载文件时进行权限检查,防止任意文件下载漏洞。

$allowed_files = [
    'file1.pdf' => 'path/to/file1.pdf',
    'file2.zip' => 'path/to/file2.zip'
];

if (isset($_GET['file']) && array_key_exists($_GET['file'], $allowed_files)) {
    $file = $allowed_files[$_GET['file']];
    // 使用上面的下载代码
} else {
    die('Invalid file request');
}

处理中文文件名

对于包含中文的文件名,需要进行编码转换。

$file = 'path/to/中文文件.pdf';
$filename = rawurlencode(basename($file));
header('Content-Disposition: attachment; filename*=UTF-8\'\'' . $filename);

这些方法涵盖了 PHP 实现文件下载的主要场景,包括基本下载、大文件处理、动态文件生成和安全防护等方面。

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

相关文章

php实现增删改查

php实现增删改查

以下是在PHP中实现增删改查(CRUD)操作的详细方法,以MySQL数据库为例: 数据库连接配置 创建config.php文件存储数据库连接信息: <?php $host = 'localh…

php实现分类

php实现分类

PHP实现分类的方法 数据库设计 创建分类表时,通常需要包含id、名称、父级id等字段。父级id用于实现多级分类结构。 CREATE TABLE categories ( id INT AU…

php实现统计

php实现统计

PHP 实现统计功能 在 PHP 中实现统计功能通常涉及数据的收集、处理和展示。以下是一些常见的统计实现方法: 数据库数据统计 通过 SQL 查询可以直接从数据库中获取统计结果: $conn =…

php实现定时

php实现定时

PHP 实现定时任务的方法 PHP 本身是脚本语言,通常需要借助外部工具或框架实现定时任务。以下是几种常见方法: 使用 Cron 任务 Linux 系统自带的 Cron 是常用的定时任务工具。通过编…

php实现过程

php实现过程

PHP 实现过程 PHP 是一种广泛使用的服务器端脚本语言,特别适合 Web 开发。以下是 PHP 实现过程的关键步骤和注意事项。 安装与配置 下载并安装 PHP,可以从官方 PHP 网站获取最新版…

java如何删除文件

java如何删除文件

删除文件的基本方法 使用 java.io.File 类的 delete() 方法可以删除文件。如果文件存在且删除成功,返回 true;否则返回 false。 import java.io…