当前位置:首页 > 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;
}

处理大文件下载

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

$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 文件。

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

处理中文文件名

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

php实现文件下载

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

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

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

相关文章

php验证码实现

php验证码实现

验证码实现方法 在PHP中实现验证码功能通常涉及生成随机字符串或数字,将其转换为图像,并通过会话(Session)进行验证。以下是几种常见的实现方式: 使用GD库生成图像验证码 GD库是PHP内置的…

php实现异步

php实现异步

PHP 实现异步的方法 PHP 本身是同步执行的脚本语言,但可以通过以下方法模拟异步操作或实现异步效果: 使用多进程(pcntl_fork) 通过 pcntl_fork 创建子进程实现异步,适用于…

基于php的设计与实现

基于php的设计与实现

PHP 设计与实现的关键要素 环境搭建与框架选择 PHP开发需配置服务器环境(如Apache/Nginx)、PHP版本(建议7.4+)及数据库(MySQL/MariaDB)。主流框架包括Laravel…

php实现博客

php实现博客

使用PHP实现博客系统 数据库设计 创建数据库表存储博客文章和用户信息。常见的表包括posts(文章)和users(用户)。 CREATE TABLE users ( id INT AUTO…

php 实现跳转

php 实现跳转

PHP 实现页面跳转的方法 在PHP中,实现页面跳转可以通过多种方式完成,以下是几种常用的方法: 使用header函数 header函数是PHP中最常用的跳转方法,通过发送HTTP头部信息实现跳转。…

如何编译react文件

如何编译react文件

编译 React 文件的方法 使用 Create React App (CRA) Create React App 是官方推荐的快速搭建 React 项目的工具,内置了 Babel 和 Webpack…