仰望星辰工作室

better-staridc-MNBT

better-staridc-MNBT/ _router.php 1.5 KB · 54 行 原始文件
Z zfhsh first commit 1 天前
1<?php
2$root = realpath(__DIR__); // 获取绝对路径,消除符号链接影响
3$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
4
5// 1. 安全过滤:去除路径中的 ../ 和 ./,防止路径遍历
6$safePath = str_replace(['../', './', '..\\', '.\\'], '', $path);
7// 确保路径以 / 开头
8if (substr($safePath, 0, 1) !== '/') {
9 $safePath = '/' . $safePath;
10}
11
12$phpFile = $root . $safePath;
13
14// 2. 核心防御:使用 realpath 解析真实路径,并检查是否在允许的 $root 目录下
15$realFile = realpath($phpFile);
16
17if ($realFile !== false && strpos($realFile, $root) === 0) {
18
19 // 处理 PHP 文件
20 if (is_file($realFile) && substr($realFile, -4) === '.php') {
21 chdir(dirname($realFile));
22 require $realFile;
23 return true;
24 }
25
26 // 处理静态资源
27 if (is_file($realFile)) {
28 $ext = pathinfo($realFile, PATHINFO_EXTENSION);
29 $mime = [
30 'css'=>'text/css',
31 'js'=>'application/javascript',
32 'png'=>'image/png',
33 'jpg'=>'image/jpeg',
34 'gif'=>'image/gif',
35 'ico'=>'image/x-icon'
36 ];
37 if (isset($mime[$ext])) {
38 header('Content-Type: ' . $mime[$ext]);
39 }
40 readfile($realFile);
41 return true;
42 }
43}
44
45// 文件未找到或路径非法:交给插件通用路由
46$commonFile = $root . '/MPHX/common.php';
47if (is_file($commonFile)) {
48 require $commonFile;
49 if (function_exists('mnbt_plugin_dispatch_route') && mnbt_plugin_dispatch_route()) {
50 return true;
51 }
52}
53
54return false;