优选小栈

BaDouCMS后台登陆密码忘记/找回密码后台登录密码工具脚本【安全增强版】

晨瑞 发布于

BaDouCMS后台管理员密码重置工具【安全增强版】

一个专为BaDouCMS后台管理系统设计的应急密码重置工具,帮助管理员在忘记密码时快速、安全地重置管理员账户密码。工具操作简单,安全可靠,无需修改数据库或复杂配置。

🔒 安全可靠

自动锁定机制:重置后可选择生成 lock 文件,立即阻止工具被再次访问
双重安全选项:提供"加锁"和"删除"两种安全操作,满足不同使用场景
访问拒绝保护:存在 lock 文件时自动显示拒绝访问页面,防止未授权使用
密码加密存储:使用 password_hash 加密,与项目保持一致的密码安全标准

🎯 智能配置

自动配置检测:优先读取 .env 文件,不存在时自动回退到 .env-example
配置来源提示:界面清晰显示当前使用的配置文件来源
灵活前缀支持:自动读取数据库前缀,适配不同项目结构

🚀 简单易用

一键部署:只需将文件上传到 public 目录即可使用
简洁界面:现代化渐变风格 UI,操作直观清晰
实时反馈:操作成功/失败即时显示,无需刷新页面
表单快速返回:支持返回表单功能,方便连续操作

🛡️ 安全保障

缓存控制:添加 HTTP 缓存控制头,防止 POST 重复提交
清空登录状态:重置密码时自动清空 token 和登录失败次数,强制重新登录
敏感操作确认:密码验证采用二次确认机制,防止误操作

使用场景

忘记管理员密码:快速重置后台管理员登录密码
密码泄露应急:紧急更换被泄露的管理员密码
测试环境使用:开发测试期间方便重置测试账号
多管理员维护:维护多个管理员账号的密码

技术特点

零依赖:无需安装任何第三方库,原生 PHP 实现
PDO 数据库连接:使用标准 PDO 方式连接,安全可靠
兼容性强:支持 PHP 7.0+ 版本
响应式设计:完美适配 PC 和移动端设备

使用说明

1.新建一个resetpwd.php文件,复制下面的完整代码。
2.访问域名/resetpwd.php 即可访问

安全提示

⚠️ 重要提醒:本工具仅限本地环境或测试环境使用,生产环境使用后务必删除或加锁,以确保系统安全!

代码预览

<?php
/**
 * 后台管理员密码重置工具
 *
 * 使用说明:
 * 1. 将脚本放到public目录后,将文件名字改成 resetpwd.php
 * 2. 访问此脚本:你的域名/resetpwd.php
 * 3. 输入要重置的管理员用户名和新密码
 * 4. 重置成功后,可选择删除或加锁此文件(必须删除或加锁,否则有安全隐患!!!)
 *
 * 安全提示:
 * - 优先从 .env 读取数据库配置,不存在则自动读取 .env-example
 * - 使用后请务必删除或加锁此文件!!!
 */

// lock文件路径
$lockFile = __DIR__ . '/resetpwd.lock';

// 检查是否存在lock文件,如果存在则阻止访问
if (file_exists($lockFile)) {
    http_response_code(403);
    echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>访问被拒绝</title></head><body style="display:flex;justify-content:center;align-items:center;height:100vh;background:#f0f0f0;"><div style="background:white;padding:40px;border-radius:10px;box-shadow:0 2px 10px rgba(0,0,0,0.1);text-align:center;"><h1 style="color:#dc3545;">🔒 访问被拒绝</h1><p>此工具已被加锁,无法访问。</p><p style="font-size:14px;color:#666;margin-top:20px;">如需再次使用,请删除 resetpwd.lock 文件。</p></div></body></html>';
    exit;
}

// 加载项目环境配置
function loadEnvConfig($envFile) {
    if (!file_exists($envFile)) {
        return [];
    }

    $config = [];
    $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

    $currentSection = '';
    foreach ($lines as $line) {
        $line = trim($line);

        // 跳过注释
        if (empty($line) || $line[0] === '#' || $line[0] === ';') {
            continue;
        }

        // 检测section
        if (preg_match('/^\[(.+)\]$/', $line, $matches)) {
            $currentSection = strtolower($matches[1]);
            continue;
        }

        // 解析键值对
        if (strpos($line, '=') !== false) {
            list($key, $value) = explode('=', $line, 2);
            $key = trim($key);
            $value = trim($value);

            if ($currentSection === 'database') {
                $config[strtolower($key)] = $value;
            }
        }
    }

    return $config;
}

// 默认配置
$envFile = __DIR__ . '/../.env';
$envExampleFile = __DIR__ . '/../.env-example';

// 优先读取 .env,不存在则读取 .env-example
if (file_exists($envFile)) {
    $envConfig = loadEnvConfig($envFile);
    $configSource = '.env';
} elseif (file_exists($envExampleFile)) {
    $envConfig = loadEnvConfig($envExampleFile);
    $configSource = '.env-example';
} else {
    $envConfig = [];
    $configSource = 'none';
}

$dbConfig = [
    'hostname' => $envConfig['hostname'] ?? '127.0.0.1',
    'database' => $envConfig['database'] ?? '',
    'username' => $envConfig['username'] ?? '',
    'password' => $envConfig['password'] ?? '',
    'port'     => $envConfig['hostport'] ?? '3306',
    'prefix'   => $envConfig['prefix'] ?? 'bd_',
    'charset'  => $envConfig['charset'] ?? 'utf8mb4',
];

$error = '';
$success = '';
$warning = '';
$configLoaded = !empty($dbConfig['database']) && !empty($dbConfig['username']);

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'lock_file') {
        // 生成lock文件
        if (file_put_contents($lockFile, date('Y-m-d H:i:s') . " - Tool locked\n")) {
            echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><meta http-equiv="refresh" content="3;url=resetpwd.php"><title>加锁成功</title><style>body{display:flex;justify-content:center;align-items:center;height:100vh;background:#f0f0f0;font-family:Arial,sans-serif;}.container{background:white;padding:40px;border-radius:10px;box-shadow:0 2px 10px rgba(0,0,0,0.1);text-align:center;}h1{color:#28a745;margin-bottom:20px;}p{color:#666;line-height:1.6;}</style></head><body><div class="container"><h1>✅ 文件已成功加锁!</h1><p>现在无法访问此工具。</p><p>如需再次使用,请删除 resetpwd.lock 文件。</p><p style="margin-top:20px;color:#999;font-size:14px;">页面将在3秒后刷新...</p></div></body></html>';
            exit;
        } else {
            $error = '文件加锁失败,请检查服务器权限。';
        }
    } elseif ($action === 'delete_file') {
        // 删除文件
        $deleteFile = __FILE__;
        if (@unlink($deleteFile)) {
            echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>删除成功</title></head><body style="display:flex;justify-content:center;align-items:center;height:100vh;background:#f0f0f0;"><div style="background:white;padding:40px;border-radius:10px;box-shadow:0 2px 10px rgba(0,0,0,0.1);text-align:center;"><h1 style="color:#28a745;">✅ 删除成功</h1><p>resetpwd.php 文件已被删除。</p></div></body></html>';
            exit;
        } else {
            $error = '文件删除失败,请手动删除此文件以确保安全。';
        }
    } elseif ($action === 'reset_password') {
        $adminUsername = trim($_POST['admin_username'] ?? '');
        $newPassword = $_POST['new_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';

        // 验证输入
        if (empty($adminUsername)) {
            $error = '请输入管理员用户名';
        } elseif (empty($newPassword)) {
            $error = '请输入新密码';
        } elseif (strlen($newPassword) < 6) {
            $error = '密码长度至少为6个字符';
        } elseif ($newPassword !== $confirmPassword) {
            $error = '两次输入的密码不一致';
        } elseif (!$configLoaded) {
            $error = '无法读取数据库配置,请检查 .env 或 .env-example 文件是否存在';
        } else {
            try {
                // 连接数据库
                $dsn = "mysql:host={$dbConfig['hostname']};port={$dbConfig['port']};dbname={$dbConfig['database']};charset={$dbConfig['charset']}";
                $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password'], [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                ]);

                // 查询管理员
                $tableName = $dbConfig['prefix'] . 'admin';
                $stmt = $pdo->prepare("SELECT id, username, email FROM `{$tableName}` WHERE username = :username LIMIT 1");
                $stmt->execute(['username' => $adminUsername]);
                $admin = $stmt->fetch();

                if (!$admin) {
                    $error = "管理员用户 '{$adminUsername}' 不存在";
                } else {
                    // 使用 password_hash 加密密码(与项目一致)
                    $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);

                    // 更新密码并清空token(强制重新登录)
                    $updateStmt = $pdo->prepare("
                        UPDATE `{$tableName}`
                        SET password = :password,
                            token = '',
                            loginfailure = 0,
                            update_time = :update_time
                        WHERE id = :id
                    ");

                    $result = $updateStmt->execute([
                        'password' => $hashedPassword,
                        'update_time' => time(),
                        'id' => $admin['id']
                    ]);

                    if ($result) {
                        $success = "密码重置成功!<br><br>";
                        $success .= "用户名: {$admin['username']}<br>";
                        $success .= "邮箱: {$admin['email']}<br><br>";
                        $success .= "<strong style='color: #d9534f;'>提示:请立即删除此文件(resetpwd.php)以确保安全!</strong>";
                    } else {
                        $error = '密码更新失败,请检查数据库权限';
                    }
                }

            } catch (PDOException $e) {
                $error = '数据库连接失败: ' . $e->getMessage();
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <title>后台管理员密码重置工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
            width: 100%;
            max-width: 500px;
            padding: 40px;
        }

        h1 {
            color: #333;
            font-size: 24px;
            margin-bottom: 10px;
            text-align: center;
        }

        .subtitle {
            color: #666;
            font-size: 14px;
            text-align: center;
            margin-bottom: 30px;
        }

        .alert {
            padding: 12px 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            font-size: 14px;
        }

        .alert-danger {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            color: #333;
            font-weight: 500;
            margin-bottom: 8px;
            font-size: 14px;
        }

        input[type="text"],
        input[type="password"] {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        button {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
        }

        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        button:active {
            transform: translateY(0);
        }

        .warning-box {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 12px 15px;
            margin-bottom: 20px;
            font-size: 13px;
            color: #856404;
        }

        .warning-box strong {
            display: block;
            margin-bottom: 5px;
        }

        .info-box {
            background: #e7f3ff;
            border-left: 4px solid #2196F3;
            padding: 12px 15px;
            margin-bottom: 20px;
            font-size: 13px;
            color: #0c5460;
        }

        .info-box strong {
            display: block;
            margin-bottom: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔐 后台密码重置工具</h1>
        <p class="subtitle">忘记密码时的应急重置工具</p>

        <div class="warning-box">
            <strong>⚠️ 安全提示</strong>
            此工具仅限本地环境使用,使用完成后请务必删除或加锁此文件!
        </div>

        <?php if ($configLoaded): ?>
            <div class="info-box">
                <strong>✓ 数据库配置已加载</strong>
                已从 <?php echo $configSource; ?> 文件自动读取数据库连接信息
            </div>
        <?php else: ?>
            <div class="alert alert-danger">
                ❌ 无法读取数据库配置文件,请确保 .env 或 .env-example 文件存在且包含数据库配置信息
            </div>
        <?php endif; ?>

        <?php if ($warning): ?>
            <div class="alert alert-warning">
                ⚠️ <?php echo htmlspecialchars($warning); ?>
            </div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="alert alert-danger">
                ❌ <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="alert alert-success">
                ✅ <?php echo $success; ?>
            </div>

            <!-- 安全操作按钮 -->
            <div class="form-group" style="margin-top: 30px;">
                <label style="margin-bottom: 15px;">请选择安全操作(必选其一):</label>
                <div style="display: flex; gap: 10px;">
                    <form method="POST" action="" style="flex: 1;">
                        <input type="hidden" name="action" value="lock_file">
                        <button type="submit" style="background: linear-gradient(135deg, #ffc107 0%, #ff9800 100%);">🔒 加锁文件</button>
                    </form>
                    <form method="POST" action="" style="flex: 1;">
                        <input type="hidden" name="action" value="delete_file">
                        <button type="submit" style="background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);">🗑️ 删除文件</button>
                    </form>
                </div>
                <p style="font-size: 12px; color: #666; margin-top: 10px; line-height: 1.5;">
                    <strong>加锁文件:</strong>生成 lock 文件阻止访问,删除 lock 文件可恢复(推荐)。<br>
                    <strong>删除文件:</strong>永久删除此文件。
                </p>
            </div>

            <!-- 返回按钮 -->
            <form method="GET" action="">
                <button type="submit" style="background: linear-gradient(135deg, #6c757d 0%, #5a6268 100%);">📝 返回重置表单</button>
            </form>
        <?php else: ?>
            <form method="POST" action="">
                <input type="hidden" name="action" value="reset_password">

                <div class="form-group">
                    <label>管理员用户名 *</label>
                    <input type="text" name="admin_username" placeholder="请输入要重置密码的管理员用户名" required autofocus>
                </div>

                <div class="form-group">
                    <label>新密码 *</label>
                    <input type="password" name="new_password" placeholder="请输入新密码(至少6位)" required>
                </div>

                <div class="form-group">
                    <label>确认密码 *</label>
                    <input type="password" name="confirm_password" placeholder="请再次输入新密码" required>
                </div>

                <button type="submit" <?php echo !$configLoaded ? 'disabled' : ''; ?>>🔄 重置密码</button>
            </form>
        <?php endif; ?>
    </div>
</body>
</html>

完整代码免费下载

BaDouCMS密码重置工具.zip


重置后一定要记得删除该工具,切记!!!;
重置后一定要记得删除该工具,切记!!!;
重置后一定要记得删除该工具,切记!!!;