PHP文件下载

流程

  1. 获取要下载的文件路径,若为网络文件在php处理时需转为本地路径
  2. php处理,判断是否为文件,或者防注入等处理参数
  3. 设置header,执行下载

页面

html 复制代码
<div>
   <h2>DOWNLOAD</h2>
   <ul>
       <li v-for="(value,key) in dirfiles" :key="key">
           <a :href="'download.php?path='+value" target="_blank">{{value}}</a>
       </li>
    </ul>
</div>

vue3

javascript 复制代码
let dirfiles =  ref(null);
function getfiles(){
        const url ="getfiles.php";
        axios.get(url).then(res=>{
                 dirfiles.value = res.data.data
        }) .catch(error => {
                 console.error('获取文件失败', error);
        });
}

php处理

php 复制代码
//getfiles.php
include_once "common.php";
$dir = PATH_UPLOAD;
function opendors($dir, $filelist = []) {
    if ($handle = opendir($dir)) {
        while (false !== ($file = readdir($handle))) {
            // 过滤掉当前目录和上一级目录
            if ($file != "." && $file != "..") {
                $path = $dir . "/" . $file;
                if (is_dir($path)) {
                    $filelist = opendors($path, $filelist);
                } elseif (is_file($path)) {
                    array_push($filelist, $path);
                }
            }
        }
        closedir($handle);
    }
    return $filelist;
}
$filelist = opendors($dir);

backjson(1, "获取成功", $filelist);
php 复制代码
//download.php
$params = $_GET;
var_dump($params);
$path = $params['path'];
if (!is_file($path)) {
    backjson(1, "文件不存在");
}
$fileinfo = pathinfo($path);
var_dump($fileinfo);
$filename = $fileinfo['basename'];
$filesize = filesize($path);

//设置表头
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $filename);
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . $filesize);
readfile($path);
exit;
相关推荐
Lhappy嘻嘻14 小时前
Java IO|File 文件操作 + 字节流 / 字符流完整笔记 + 递归删除文件实战
java·笔记·php
2601_9637713716 小时前
How to Scale Your WordPress Store Traffic in 2026
前端·php·plugin
右耳朵猫AI20 小时前
PHP周刊2026W28 | 安全更新、Laravel 13.18、Twig 3.28
开发语言·php·laravel
罗政20 小时前
PDF 批量合并工具:本地 AI 自动排序、识别正文日期与合同编号
数据库·pdf·php
糖果店的幽灵1 天前
安全测试从入门到精通_网络基础与HTTPS
网络·https·php
2601_963771371 天前
WordPress SEO Guide: Boost Rankings Without Technical Jargon
前端·php
日取其半万世不竭1 天前
CS2 服务器搜不到?GSLT、端口和启动参数逐项检查
运维·服务器·php
360智汇云1 天前
一次Redis超时引发的“冤案“
数据库·redis·php
ljs6482739511 天前
Linux 网络常用命令与端口基础详解
linux·网络·php
m0_738120722 天前
PHP代码审计基础——超全局变量(三)
开发语言·安全·网络安全·php