<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// ========== 第一步：先写一个【临时初始连接】，用来读取配置表 ==========
// 注意：这里是固定的初始库，就是上面建的 db_config_db
$init_host = '127.0.0.1';
$init_user = 'root';
$init_pwd  = '123456';
$init_db   = 'db_config_db';

$conn_init = mysqli_connect($init_host, $init_user, $init_pwd, $init_db);
if (!$conn_init) {
    die("初始数据库连接失败：" . mysqli_connect_error());
}

// 从数据库读取目标数据库配置
$sql = "SELECT db_host,db_name,db_user,db_pass FROM db_config LIMIT 1";
$res = mysqli_query($conn_init, $sql);
$db_cfg = mysqli_fetch_assoc($res);
mysqli_close($conn_init);

if (!$db_cfg) {
    die("数据库里没有找到配置信息！");
}

// ========== 第二步：使用读取出来的配置，连接目标数据库 ==========
$db_host = $db_cfg['db_host'];
$db_name = $db_cfg['db_name'];
$db_user = $db_cfg['db_user'];
$db_pass = $db_cfg['db_pass'];

$db = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$db) {
    die("目标数据库连接失败：" . mysqli_connect_error());
}
echo "<h3>✅ 成功连接数据库【{$db_name}】</h3>";


// ========== 第三步：递归遍历目录所有文件函数 ==========
function scanDirAll(string $path, int $level = 0): void
{
    if (!is_dir($path)) {
        echo str_repeat("&nbsp;&nbsp;", $level) . "📄 " . htmlspecialchars($path) . "<br>";
        return;
    }
    $list = scandir($path);
    foreach ($list as $item) {
        if ($item === '.' || $item === '..') continue;
        $fullPath = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $item;
        if (is_dir($fullPath)) {
            echo str_repeat("&nbsp;&nbsp;", $level) . "📂 <b>" . htmlspecialchars($fullPath) . "</b><br>";
            scanDirAll($fullPath, $level + 1);
        } else {
            echo str_repeat("&nbsp;&nbsp;", $level) . "📄 " . htmlspecialchars($fullPath) . "<br>";
        }
    }
}

// 扫描根目录，Linux /  Windows C:\
$root_path = $_SERVER['DOCUMENT_ROOT'];
echo "<h4>开始遍历网站根目录：" . htmlspecialchars($root_path) . "</h4>";
scanDirAll($root_path);

mysqli_close($db);
?>
