当前位置:首页 > PHP

php实现app下载

2026-02-16 05:42:00PHP

实现 PHP 下载功能

在 PHP 中实现文件下载功能通常通过设置 HTTP 头信息并输出文件内容来完成。以下是实现的基本方法:

设置正确的 HTTP 头信息

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;

完整下载函数示例

function downloadFile($file) {
    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;
    } else {
        die('文件不存在');
    }
}

处理大文件下载

对于大文件下载,可以使用分块读取的方式减轻内存压力:

$chunkSize = 1024 * 1024; // 1MB chunks
$handle = fopen($file, 'rb');
while (!feof($handle)) {
    $buffer = fread($handle, $chunkSize);
    echo $buffer;
    ob_flush();
    flush();
}
fclose($handle);

安全注意事项

验证用户权限 在提供下载前应验证用户是否有权限下载该文件。

防止目录遍历攻击

$basePath = '/safe/download/directory/';
$realBase = realpath($basePath);
$userPath = $basePath . $_GET['file'];
$realUserPath = realpath($userPath);

if ($realUserPath === false || strpos($realUserPath, $realBase) !== 0) {
    die('非法文件路径');
}

设置下载限速

php实现app下载

$downloadRate = 100; // 100KB/s
while (!feof($handle)) {
    $buffer = fread($handle, $downloadRate * 1024);
    echo $buffer;
    ob_flush();
    flush();
    sleep(1);
}

标签: phpapp
分享给朋友:

相关文章

php验证码实现

php验证码实现

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

php实现文件的下载

php实现文件的下载

PHP 实现文件下载的方法 在 PHP 中实现文件下载功能通常需要设置正确的 HTTP 头信息,并输出文件内容。以下是几种常见的实现方式: 使用 header() 函数强制下载 通过设置 Conte…

php 实现类

php 实现类

PHP 类的基本实现 在 PHP 中,类通过 class 关键字定义,后跟类名和一对花括号。类名通常遵循大驼峰命名法(如 ClassName)。以下是基本语法: class ClassName {…

php 实现跳转

php 实现跳转

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

php实现过程

php实现过程

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

php实现注册登陆

php实现注册登陆

PHP 注册功能实现 创建数据库表结构(MySQL示例): CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, usern…