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;
相关推荐
八月的雨季 最後的冰吻3 小时前
php算法-- 关联数组使用,优化sip账号去重
开发语言·php
rockmelodies11 小时前
【PHP安全】免费解密支持:zend52、zend53、zend54好工具
开发语言·安全·php
速易达网络18 小时前
PHP 与 Vue.js 结合的前后端分离架构
vue.js·php
Clownseven1 天前
使用 eBPF 实时捕获 TCP 重传告警:精准定位网络抖动问题
网络·tcp/ip·php
行思理1 天前
如何使用 php-vulnerability-hunter
开发语言·php
hjc_0420431 天前
云效CI/CD教程(PHP项目)
ci/cd·php
MonkeyPromise2 天前
网络编程初识(详细易懂)
服务器·网络·php
uwvwko2 天前
使用docker(ubuntu)搭建web环境(php,apahce2)
ubuntu·docker·php·web·ctf·apache2