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;
相关推荐
ooseabiscuit9 小时前
Laravel4.x:现代PHP框架的奠基之作
java·开发语言·php
ooseabiscuit11 小时前
Laravel 1.x:揭秘PHP框架的起源与设计
php·laravel
m0_7381207211 小时前
ctfshow靶场SSRF部分——基础绕过到协议攻击解题思路与技巧(一)
服务器·前端·网络·安全·php
幽络源小助理14 小时前
最新短网址系统源码 分用户链接 - 幽络源免费源码分享
前端·php
ooseabiscuit14 小时前
Laravel5
android·php·laravel
神仙别闹19 小时前
基于PHP+MySQL实现在线考试系统
开发语言·mysql·php
棒棒的唐20 小时前
配置 VSCode 的 PHP Intelephense 插件,去掉因php版本不同导至的红色波浪线误判
ide·vscode·php
Mike117.20 小时前
GBase 8a DBLink 查询的落地边界和排查细节
开发语言·php
ooseabiscuit21 小时前
PHP与C++:Web与系统编程的终极对决
前端·c++·php
ooseabiscuit1 天前
Laravel 8.x核心特性深度解析
php·laravel