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;
相关推荐
JaguarJack13 小时前
为什么 PHP 闭包要加 static?
后端·php·服务端
ServBay2 天前
垃圾堆里编码?真的不要怪 PHP 不行
后端·php
用户962377954482 天前
CTF 伪协议
php
BingoGo4 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php
JaguarJack4 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php·服务端
BingoGo5 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php
JaguarJack5 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php·服务端
JaguarJack6 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
后端·php·服务端
BingoGo6 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
php
JaguarJack7 天前
告别 Laravel 缓慢的 Blade!Livewire Blaze 来了,为你的 Laravel 性能提速
后端·php·laravel