Admin Panel for Rookies & Pros:

The MySQL DBA Toolkit is a lightweight, session-based admin panel designed for database administrators who value clarity, reproducibility, and security. Built by the IT-INDIA.org community, this toolkit strips away the clutter of bloated UIs like phpMyAdmin and delivers clean, functional tools for everyday DBA tasks.

⚙️ Features

  • Session-Based Login: Authenticate using MySQL root password, stored only in memory.
  • Provisioning: Create databases and users with full privileges and config-ready output.
  • Cleanup: Drop databases and users safely with confirmation prompts.
  • Backup & Download: Generate .sql and .zip dumps, download instantly, and manage backups via backup-manager.php.

You also might wanna view GitHub readme for MySQL DBA ToolKit.


DBA ToolKit - Home
DBA ToolKit – Home
<?php
// index.php - Complete Database Administration Toolkit - ; SS above;

session_start();

// Handle file downloads FIRST - before any output
if (isset($_GET['download'])) {
    $file = $_GET['download'];
    if (file_exists($file) && strpos(realpath($file), realpath('/tmp/backups/')) === 0) {
        $filename = basename($file);
        $extension = pathinfo($file, PATHINFO_EXTENSION);
        
        // Clear any output buffers
        while (ob_get_level()) {
            ob_end_clean();
        }
        
        // Set appropriate headers based on file type
        if ($extension === 'zip') {
            header('Content-Type: application/zip');
        } elseif ($extension === 'sql') {
            header('Content-Type: application/sql');
        } else {
            header('Content-Type: application/octet-stream');
        }
        
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . filesize($file));
        header('Cache-Control: no-cache, must-revalidate');
        header('Pragma: no-cache');
        header('Expires: 0');
        
        // Output file content
        readfile($file);
        exit;
    } else {
        // File not found or outside allowed directory - redirect back with error
        header('Location: ?tool=backup&error=file_not_found');
        exit;
    }
}

$page_title = "DBA Toolkit by IT-INDIA.org";
$current_tool = $_GET['tool'] ?? 'home';

// Check if user is logged in (has root password in session)
$is_logged_in = isset($_SESSION['mysql_root_password']);

// Handle logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: ?tool=home');
    exit;
}

// Handle login form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'login') {
    $root_password = $_POST['root_password'] ?? '';
    
    if (!empty($root_password)) {
        // Test the connection with provided credentials
        try {
            $pdo = new PDO("mysql:host=localhost", 'root', $root_password);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            
            // Store password in session if connection successful
            $_SESSION['mysql_root_password'] = $root_password;
            $is_logged_in = true;
            
            // Redirect to home page
            header('Location: ?tool=home');
            exit;
        } catch (PDOException $e) {
            $login_error = "Failed to connect: " . $e->getMessage();
        }
    } else {
        $login_error = "Please enter the MySQL root password";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>
    <style>
        :root {
            --primary: #007bff;
            --primary-dark: #0056b3;
            --success: #28a745;
            --danger: #dc3545;
            --warning: #ffc107;
            --info: #17a2b8;
            --light: #f8f9fa;
            --dark: #343a40;
            --gray: #6c757d;
            --sidebar-width: 250px;
        }
        
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
            position: relative;
            padding-bottom: 80px; /* Added space for footer */
        }
        
        .app-container {
            max-width: 1600px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
            display: flex;
            min-height: 800px;
        }
        
        /* Footer Styles */
        .footer {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            text-align: center;
            padding: 20px;
            background: rgba(255, 255, 255, 0.1);
            color: white;
            font-size: 0.9em;
            margin-top: 30px;
            border-top: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .footer p {
            margin: 0;
            opacity: 0.9;
        }
        
        /* Login overlay */
        .login-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        
        .login-form {
            background: white;
            padding: 30px;
            border-radius: 12px;
            width: 400px;
            max-width: 90%;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
        }
        
        .login-form h2 {
            text-align: center;
            margin-bottom: 20px;
            color: var(--primary);
        }
        
        /* Sidebar Navigation */
        .sidebar {
            width: var(--sidebar-width);
            background: var(--dark);
            color: white;
            padding: 0;
        }
        
        .sidebar-header {
            padding: 25px;
            background: rgba(0,0,0,0.2);
            text-align: center;
        }
        
        .sidebar-header h1 {
            font-size: 1.5em;
            margin-bottom: 5px;
            color: white;
        }
        
        .sidebar-header p {
            opacity: 0.8;
            font-size: 0.9em;
        }
        
        .nav-menu {
            list-style: none;
            padding: 20px 0;
        }
        
        .nav-item {
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        
        .nav-link {
            display: block;
            padding: 15px 25px;
            color: white;
            text-decoration: none;
            transition: all 0.3s ease;
            font-weight: 500;
        }
        
        .nav-link:hover {
            background: rgba(255,255,255,0.1);
            padding-left: 30px;
        }
        
        .nav-link.active {
            background: var(--primary);
            border-left: 4px solid var(--warning);
        }
        
        /* Main Content */
        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
        }
        
        .content-header {
            background: var(--primary);
            color: white;
            padding: 20px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .content-header h2 {
            font-size: 1.8em;
            font-weight: 300;
        }
        
        .logout-btn {
            background: rgba(255,255,255,0.2);
            color: white;
            padding: 8px 15px;
            border-radius: 6px;
            text-decoration: none;
            transition: all 0.3s ease;
        }
        
        .logout-btn:hover {
            background: rgba(255,255,255,0.3);
        }
        
        .tool-content {
            flex: 1;
            padding: 30px;
            overflow-y: auto;
            background: var(--light);
        }
        
        /* Two-column layout for tools */
        .columns-container {
            display: flex;
            gap: 30px;
            min-height: 600px;
        }
        
        .form-column {
            flex: 1;
            background: white;
            padding: 25px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }
        
        .output-column {
            flex: 1;
            background: white;
            padding: 25px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            overflow-y: auto;
            max-height: 600px;
        }
        
        /* Form Styles */
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: var(--dark);
        }
        
        input[type="text"], 
        input[type="password"],
        input[type="file"],
        select {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }
        
        input:focus, select:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(0,123,255,0.1);
        }
        
        button {
            background: var(--primary);
            color: white;
            padding: 15px 25px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
        }
        
        button:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,123,255,0.3);
        }
        
        /* Message Styles */
        .success { background: #d4edda; color: #155724; padding: 20px; border-radius: 8px; border-left: 4px solid var(--success); margin-bottom: 20px; }
        .error { background: #f8d7da; color: #721c24; padding: 20px; border-radius: 8px; border-left: 4px solid var(--danger); margin-bottom: 20px; }
        .info { background: #d1ecf1; color: #0c5460; padding: 20px; border-radius: 8px; border-left: 4px solid var(--info); margin-bottom: 20px; }
        .warning { background: #fff3cd; color: #856404; padding: 20px; border-radius: 8px; border-left: 4px solid var(--warning); margin-bottom: 20px; }
        
        .code {
            background: #2d3748;
            color: #e2e8f0;
            padding: 20px;
            border-radius: 8px;
            font-family: 'Fira Code', monospace;
            font-size: 14px;
            line-height: 1.5;
            overflow-x: auto;
            margin-bottom: 20px;
        }
        
        .output-placeholder {
            text-align: center;
            color: var(--gray);
            padding: 60px 20px;
            font-style: italic;
        }
        
        /* Responsive */
        @media (max-width: 1200px) {
            .columns-container {
                flex-direction: column;
            }
            
            .sidebar {
                width: 200px;
            }
        }
        
        @media (max-width: 768px) {
            .app-container {
                flex-direction: column;
            }
            
            .sidebar {
                width: 100%;
                order: 2;
            }
            
            .main-content {
                order: 1;
            }
            
            .nav-menu {
                display: flex;
                flex-wrap: wrap;
                justify-content: center;
                padding: 10px;
            }
            
            .nav-item {
                border-bottom: none;
                margin: 5px;
            }
            
            .nav-link {
                padding: 10px 15px;
                border-radius: 6px;
                background: rgba(255,255,255,0.1);
            }
            
            body {
                padding-bottom: 100px; /* More space for footer on mobile */
            }
            
            .footer {
                font-size: 0.8em;
                padding: 15px;
            }
        }
        
        /* Animations */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .fade-in {
            animation: fadeIn 0.5s ease-out;
        }
        
        /* Homepage */
        .welcome-container {
            text-align: center;
            padding: 40px 20px;
        }
        
        .welcome-container h2 {
            font-size: 2.5em;
            color: var(--primary);
            margin-bottom: 20px;
        }
        
        .feature-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 40px;
        }
        
        .feature-card {
            background: white;
            padding: 25px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            text-align: center;
        }
        
        .feature-card h3 {
            color: var(--primary);
            margin-bottom: 15px;
        }
        
        .feature-icon {
            font-size: 3em;
            margin-bottom: 15px;
            color: var(--primary);
        }
    </style>
</head>
<body>
    <?php if (!$is_logged_in): ?>
    <div class="login-overlay">
        <div class="login-form fade-in">
            <h2>🔒 DBA Toolkit Login</h2>
            <?php if (isset($login_error)): ?>
                <div class="error"><?php echo $login_error; ?></div>
            <?php endif; ?>
            <form method="post" action="">
                <input type="hidden" name="action" value="login">
                <div class="form-group">
                    <label for="root_password">MySQL Root Password:</label>
                    <input type="password" id="root_password" name="root_password" required placeholder="Enter MySQL root password">
                </div>
                <button type="submit">🔓 Login</button>
            </form>
            <div class="info" style="margin-top: 20px;">
                <p>Your password is stored only in your current session and will be cleared when you logout or close your browser.</p>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <div class="app-container">
        <!-- Sidebar Navigation -->
        <nav class="sidebar">
            <div class="sidebar-header">
                <h1>🚀 DBA Toolkit</h1>
                <p>Database Administration Made Easy by <a href="https://www.it-india.org" style="color: inherit; font-weight: bold; text-decoration: none;">IT-INDIA.org</a></p>
            </div>
            <ul class="nav-menu">
                <li class="nav-item"><a href="?tool=home" class="nav-link <?php echo $current_tool == 'home' ? 'active' : ''; ?>">🏠 Home</a></li>
                <li class="nav-item"><a href="?tool=create" class="nav-link <?php echo $current_tool == 'create' ? 'active' : ''; ?>">🆕 Create DB & User</a></li>
                <li class="nav-item"><a href="?tool=drop" class="nav-link <?php echo $current_tool == 'drop' ? 'active' : ''; ?>">🗑️ Drop DB & User</a></li>
                <li class="nav-item"><a href="?tool=backup" class="nav-link <?php echo $current_tool == 'backup' ? 'active' : ''; ?>">💾 Backup & Download</a></li>
                <li class="nav-item"><a href="https://www.it-india.net/dba-tools/backup-manager.php" class="nav-link" target="_blank">👨🏻‍💼 Backup Manager</a></li>
<!--                <li class="nav-item"><a href="?tool=users" class="nav-link <?php echo $current_tool == 'users' ? 'active' : ''; ?>">👥 Manage Users</a></li> -->
                <li class="nav-item"><a href="?tool=monitor" class="nav-link <?php echo $current_tool == 'monitor' ? 'active' : ''; ?>">📊 Monitor</a></li>  
            </ul>
        </nav>



        <!-- Main Content -->
        <main class="main-content">
            <div class="content-header">
                <h2>
                    <?php
                    $tool_titles = [
                        'home' => 'Welcome to DBA Toolkit',
                        'create' => 'Create Database & User',
                        'drop' => 'Drop Database & User',
                        'backup' => 'Backup & Download Database',
                        'users' => 'Manage Database Users',
                        'monitor' => 'Database Monitoring'
                    ];
                    echo $tool_titles[$current_tool] ?? 'DBA Toolkit';
                    ?>
                </h2>
                <?php if ($is_logged_in): ?>
                <a href="?logout=1" class="logout-btn">🚪 Logout</a>
                <?php endif; ?>
            </div>

            <div class="tool-content">
                <?php
                // Show error message if file not found
                if (isset($_GET['error']) && $_GET['error'] === 'file_not_found') {
                    echo '<div class="error fade-in">File not found or has been deleted.</div>';
                }
                
                // Check if user is logged in before showing tools
                if (!$is_logged_in) {
                    echo '<div class="error">Please login first to access the DBA tools.</div>';
                } else {
                    // Include the appropriate tool
                    switch ($current_tool) {
                        case 'home':
                            include 'tool_home.php';
                            break;
                        case 'create':
                            include 'tool_create.php';
                            break;
                        case 'drop':
                            include 'tool_drop.php';
                            break;
                        case 'backup':
                            include 'tool_backup.php';
                            break;
                        case 'users':
                            echo '<div class="info">🚧 User Management tool coming soon!</div>';
                            break;
                        case 'monitor':
                            include 'tool_monitor.php';
                            break;
                        default:
                            include 'tool_home.php';
                    }
                }
                ?>
            </div>
        </main>
    </div>
    
    <!-- Footer -->
    <footer class="footer">
        <p>No Ads, No Paywalls, 100% Open-Source, Techie's life made easy by <a href="https://www.it-india.org" style="color: inherit; font-weight: bold; text-decoration: none;">IT-INDIA.org</a></p>
    </footer>
</body>
</html>

Created DB n User SS-01
Created DB n User SS-01
DB n User SS - after Creation
DB n User SS – after Creation

<?php
// tool_create.php - Below is the code to create DB & User, 
// ScreenShots (SS) above

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['db_name'])) {
    // Get the root password from session
    $root_password = $_SESSION['mysql_root_password'] ?? '';
    
    if (empty($root_password)) {
        echo '<div class="error fade-in">Please login first to create databases.</div>';
    } else {
        $db_name = $_POST['db_name'] ?? '';
        $db_user = $_POST['db_user'] ?? '';
        $db_password = $_POST['db_password'] ?? '';
        
        if (!empty($db_name) && !empty($db_user) && !empty($db_password)) {
            try {
                // Connect as root using session password
                $pdo = new PDO("mysql:host=localhost", 'root', $root_password);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                
                $output = [];
                
                // 1. Create database
                $pdo->exec("CREATE DATABASE IF NOT EXISTS `$db_name`");
                $output[] = "✅ Database '$db_name' created";
                
                // 2. Create user
                $pdo->exec("CREATE USER IF NOT EXISTS '$db_user'@'localhost' IDENTIFIED BY '$db_password'");
                $output[] = "✅ User '$db_user' created";
                
                // 3. Grant privileges
                $pdo->exec("GRANT ALL PRIVILEGES ON `$db_name`.* TO '$db_user'@'localhost'");
                $pdo->exec("FLUSH PRIVILEGES");
                $output[] = "✅ Privileges granted to '$db_user' on database '$db_name'";
                
                // Generate config file content
                $config_content = <<<EOT
<?php
// config_db.php - Auto-generated database configuration
define('DB_SERVER', 'localhost');
define('DB_USERNAME', '$db_user');
define('DB_PASSWORD', '$db_password');
define('DB_NAME', '$db_name');

try {
    \$pdo = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
    \$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    \$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch(PDOException \$e) {
    die("ERROR: Could not connect. " . \$e->getMessage());
}
?>
EOT;
                
                echo '<div class="success fade-in">';
                echo '<h3>✅ Database & User Setup Completed!</h3>';
                echo implode('<br>', $output);
                echo '</div>';
                
                echo '<div class="info fade-in">';
                echo '<h4>📋 Next Steps:</h4>';
                echo 'The database and user have been created. Now you can:';
                echo '<ol>';
                echo '<li>Use the generated config file below in your PHP applications</li>';
                echo '<li>Connect as the new user to create tables and insert data</li>';
                echo '<li>Use phpMyAdmin or command line to manage your database</li>';
                echo '</ol>';
                echo '</div>';
                
                echo '<div class="code fade-in">';
                echo '<h4>📁 config_db.php content:</h4>';
                echo '<pre>' . htmlspecialchars($config_content) . '</pre>';
                echo '<p>Copy this content and save it as <strong>config_db.php</strong> in your project directory.</p>';
                echo '</div>';
                
            } catch (PDOException $e) {
                echo '<div class="error fade-in">';
                echo '❌ Error: ' . $e->getMessage();
                echo '<br>Check your MySQL root password and try again.';
                echo '</div>';
            }
        } else {
            echo '<div class="error fade-in">Please fill all fields!</div>';
        }
    }
}
?>

<div class="columns-container">
    <!-- Form Column -->
    <div class="form-column">
        <form method="post" action="?tool=create">
            <div class="form-group">
                <label for="db_name">Database Name:</label>
                <input type="text" id="db_name" name="db_name" required placeholder="e.g., myapp_db">
            </div>
            
            <div class="form-group">
                <label for="db_user">Database User:</label>
                <input type="text" id="db_user" name="db_user" required placeholder="e.g., myapp_user">
            </div>
            
            <div class="form-group">
                <label for="db_password">Database User Password:</label>
                <input type="password" id="db_password" name="db_password" required placeholder="Strong password">
            </div>
            
            <button type="submit">🚀 Create Database & User</button>
        </form>
        
        <div class="info" style="margin-top: 20px;">
            <h4>ℹ️ Note:</h4>
            <p>Using MySQL root password from your current session. No need to enter it again.</p>
        </div>
    </div>
    
    <!-- Output Column -->
    <div class="output-column">
        <?php if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['db_name'])): ?>
        <div class="output-placeholder">
            <h3>👈 Fill out the form to create a database</h3>
            <p>Your setup results will appear here after submission</p>
        </div>
        <?php endif; ?>
    </div>
</div>

Drop DB SS 01
Drop DB SS 01
Drop DB and User SS 02
Drop DB and User SS 02
<?php
// tool_drop.php - Updated to use session password
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['db_name'])) {
    // Get the root password from session
    $root_password = $_SESSION['mysql_root_password'] ?? '';
    
    if (empty($root_password)) {
        echo '<div class="error fade-in">Please login first to drop databases.</div>';
    } else {
        $db_name = $_POST['db_name'];
        $db_user = $_POST['db_user'];
        $confirmation = $_POST['confirmation'] ?? '';
        
        if (!empty($db_name) && !empty($db_user)) {
            if ($confirmation === 'DELETE') {
                try {
                    $pdo = new PDO("mysql:host=localhost", 'root', $root_password);
                    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    
                    $output = [];
                    
                    // Drop database
                    $pdo->exec("DROP DATABASE IF EXISTS `$db_name`");
                    $output[] = "✅ Database '$db_name' dropped";
                    
                    // Drop user
                    $pdo->exec("DROP USER IF EXISTS '$db_user'@'localhost'");
                    $output[] = "✅ User '$db_user' dropped";
                    
                    $pdo->exec("FLUSH PRIVILEGES");
                    
                    echo '<div class="success fade-in">';
                    echo '<h3>✅ Database & User Removal Completed!</h3>';
                    echo implode('<br>', $output);
                    echo '</div>';
                    
                } catch (PDOException $e) {
                    echo '<div class="error fade-in">';
                    echo '❌ Error: ' . $e->getMessage();
                    echo '</div>';
                }
            } else {
                echo '<div class="error fade-in">';
                echo '❌ Please type "DELETE" in the confirmation box to proceed';
                echo '</div>';
            }
        } else {
            echo '<div class="error fade-in">Please fill all required fields!</div>';
        }
    }
}
?>

<div class="columns-container">
    <!-- Form Column -->
    <div class="form-column">
        <form method="post" action="?tool=drop">
            <div class="warning">
                <h4>⚠️ Warning: Destructive Operation</h4>
                <p>This action will permanently delete the database and user. This cannot be undone!</p>
            </div>
            
            <div class="form-group">
                <label for="db_name">Database Name to Drop:</label>
                <input type="text" id="db_name" name="db_name" required placeholder="e.g., myapp_db">
            </div>
            
            <div class="form-group">
                <label for="db_user">Database User to Drop:</label>
                <input type="text" id="db_user" name="db_user" required placeholder="e.g., myapp_user">
            </div>
            
            <div class="form-group">
                <label for="confirmation">Type "DELETE" to confirm:</label>
                <input type="text" id="confirmation" name="confirmation" required placeholder="DELETE" style="border-color: var(--danger);">
            </div>
            
            <button type="submit" style="background: var(--danger);">🗑️ Drop Database & User</button>
        </form>
        
        <div class="info" style="margin-top: 20px;">
            <h4>ℹ️ Note:</h4>
            <p>Using MySQL root password from your current session. No need to enter it again.</p>
        </div>
    </div>
    
    <!-- Output Column -->
    <div class="output-column">
        <?php if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['db_name'])): ?>
        <div class="output-placeholder">
            <h3>⚠️ Dangerous Operation</h3>
            <p>This tool will permanently remove databases and users. Use with caution!</p>
            <div class="info">
                <h4>Safety Features:</h4>
                <ul>
                    <li>Confirmation requirement</li>
                    <li>No accidental deletions</li>
                    <li>Clear warnings</li>
                </ul>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>
Backup n DL DB SS-01
Backup n DL DB SS-01
Backup n DL DB SS-02
Backup n DL DB SS-02
<?php
// tool_backup.php - Backup and Download (DB) DB

// Handle backup preview
if (isset($_GET['view'])) {
    $file = $_GET['view'];
    if (file_exists($file)) {
        $content = file_get_contents($file);
        $line_count = count(file($file));
        $file_size = round(filesize($file) / 1024, 2);
        
        echo '<div class="fade-in">';
        echo '<div style="background: var(--info); color: white; padding: 15px; border-radius: 8px 8px 0 0; margin-bottom: 0;">';
        echo '<h4 style="margin: 0;">👀 Backup Preview: ' . basename($file) . '</h4>';
        echo '<p style="margin: 5px 0 0 0;">Lines: ' . $line_count . ' | Size: ' . $file_size . ' KB</p>';
        echo '</div>';
        echo '<div class="code" style="border-radius: 0 0 8px 8px; margin-top: 0;">';
        echo '<pre style="max-height: 500px; overflow: auto; margin: 0;">' . htmlspecialchars($content) . '</pre>';
        echo '</div>';
        echo '<div style="text-align: center; margin: 20px 0;">';
        echo '<a href="?tool=backup&download=' . urlencode($file) . '" class="button" style="background: var(--success); padding: 10px 20px; border-radius: 6px; text-decoration: none; color: white; margin-right: 10px;">📄 Download This Backup</a>';
        echo '<a href="?tool=backup" class="button" style="background: var(--gray); padding: 10px 20px; border-radius: 6px; text-decoration: none; color: white;">← Back to Backup Tool</a>';
        echo '</div>';
        echo '</div>';
        return; // Exit early to show only preview
    }
}

// Handle backup creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'backup') {
    // Get the root password from session
    $root_password = $_SESSION['mysql_root_password'] ?? '';
    
    if (empty($root_password)) {
        echo '<div class="error fade-in">Please login first to create backups.</div>';
    } else {
        $db_name = $_POST['db_name'];
        
        if (!empty($db_name)) {
            try {
                $backup_dir = '/tmp/backups/';
                if (!is_dir($backup_dir)) {
                    mkdir($backup_dir, 0755, true);
                }
                
                $timestamp = date('Y-m-d_H-i-s');
                $backup_file = $backup_dir . $db_name . '_' . $timestamp . '.sql';
                $zip_file = $backup_dir . $db_name . '_' . $timestamp . '.zip';
                
                // Backup database with proper formatting and line breaks
                $command = "mysqldump -u root -p'$root_password' --skip-comments --complete-insert --skip-dump-date $db_name 2>/dev/null";
                $output = shell_exec($command);
                
                if ($output) {
                    // Add proper header and formatting
                    $header = "-- MySQL Backup Generated by DBA Toolkit\n";
                    $header .= "-- Date: " . date('Y-m-d H:i:s') . "\n";
                    $header .= "-- Database: $db_name\n";
                    $header .= "-- ------------------------------------------------------\n\n";
                    
                    $content = $header . $output;
                    
                    // Format INSERT statements with line breaks
                    $content = preg_replace_callback(
                        '/INSERT INTO `([^`]+)` VALUES (\([^)]+\))(,*)/',
                        function($matches) {
                            $values = $matches[2];
                            // Add line breaks after each row
                            $formatted_values = preg_replace('/\),\(/', "),\n(", $values);
                            return "INSERT INTO `" . $matches[1] . "` VALUES " . $formatted_values . $matches[3];
                        },
                        $content
                    );
                    
                    file_put_contents($backup_file, $content);
                    
                    // Create ZIP file
                    $zip = new ZipArchive();
                    if ($zip->open($zip_file, ZipArchive::CREATE) === TRUE) {
                        $zip->addFile($backup_file, basename($backup_file));
                        $zip->close();
                    }
                    
                    $file_size = round(filesize($backup_file) / 1024, 2);
                    $zip_size = round(filesize($zip_file) / 1024, 2);
                    $line_count = count(file($backup_file));
                    
                    echo '<div class="success fade-in">';
                    echo '<h3>✅ Backup Completed Successfully!</h3>';
                    echo "Database: <strong>$db_name</strong><br>";
                    echo "Backup file: <strong>" . basename($backup_file) . "</strong><br>";
                    echo "File size: <strong>$file_size KB</strong> (SQL), <strong>$zip_size KB</strong> (ZIP)<br>";
                    echo "Lines: <strong>$line_count</strong><br>";
                    echo '<div style="margin-top: 15px;">';
                    echo '<a href="?tool=backup&download=' . urlencode($zip_file) . '" class="button" style="background: var(--success); padding: 10px 20px; border-radius: 6px; text-decoration: none; color: white; margin-right: 10px;">📦 Download ZIP Backup</a>';
                    echo '<a href="?tool=backup&download=' . urlencode($backup_file) . '" class="button" style="background: var(--info); padding: 10px 20px; border-radius: 6px; text-decoration: none; color: white; margin-right: 10px;">📄 Download SQL Backup</a>';
                    echo '<a href="?tool=backup&view=' . urlencode($backup_file) . '" class="button" style="background: var(--warning); padding: 10px 20px; border-radius: 6px; text-decoration: none; color: var(--dark);">👀 Preview Backup</a>';
                    echo '</div>';
                    echo '</div>';
                } else {
                    throw new Exception('Backup failed. Check database name.');
                }
                
            } catch (Exception $e) {
                echo '<div class="error fade-in">';
                echo '<h3>⚠ Error</h3>';
                echo $e->getMessage();
                echo '</div>';
            }
        }
    }
}

// List existing backups
$backup_dir = '/tmp/backups/';
$backups = [];
if (is_dir($backup_dir)) {
    $files = scandir($backup_dir);
    foreach ($files as $file) {
        if ($file !== '.' && $file !== '..' && (pathinfo($file, PATHINFO_EXTENSION) === 'sql' || pathinfo($file, PATHINFO_EXTENSION) === 'zip')) {
            $backups[] = $file;
        }
    }
    rsort($backups); // Sort newest first
}
?>

<div class="columns-container">
    <div class="form-column">
        <!-- Backup Form -->
        <form method="post" action="?tool=backup" style="margin-bottom: 30px; padding: 20px; background: #f8f9fa; border-radius: 8px;">
            <h3>📤 Backup Database</h3>
            <input type="hidden" name="action" value="backup">
            
            <div class="form-group">
                <label for="backup_db_name">Database Name:</label>
                <input type="text" name="db_name" required placeholder="e.g., myapp_db">
            </div>
            
            <button type="submit">💾 Create Backup</button>
        </form>
        
        <div class="info">
            <h4>ℹ️ Note:</h4>
            <p>Using MySQL root password from your current session. No need to enter it again.</p>
        </div>
    </div>
    
    <div class="output-column">
        <?php if (!empty($backups)): ?>
        <h3>📦 Existing Backups</h3>
        <div style="max-height: 400px; overflow-y: auto;">
            <table style="width: 100%; border-collapse: collapse;">
                <thead>
                    <tr style="background: var(--primary); color: white;">
                        <th style="padding: 10px; text-align: left;">File Name</th>
                        <th style="padding: 10px; text-align: center;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($backups as $index => $backup): ?>
                    <tr style="background: <?php echo $index % 2 === 0 ? '#f8f9fa' : 'white'; ?>;">
                        <td style="padding: 10px; border-bottom: 1px solid #ddd;"><?php echo htmlspecialchars($backup); ?></td>
                        <td style="padding: 10px; border-bottom: 1px solid #ddd; text-align: center;">
                            <?php
                            $file_path = $backup_dir . $backup;
                            $extension = pathinfo($backup, PATHINFO_EXTENSION);
                            ?>
                            <a href="?tool=backup&download=<?php echo urlencode($file_path); ?>" style="background: var(--success); color: white; padding: 5px 10px; border-radius: 4px; text-decoration: none; margin-right: 5px;" title="Download">📥</a>
                            <?php if ($extension === 'sql'): ?>
                            <a href="?tool=backup&view=<?php echo urlencode($file_path); ?>" style="background: var(--warning); color: var(--dark); padding: 5px 10px; border-radius: 4px; text-decoration: none;" title="Preview">👀</a>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php else: ?>
        <div class="output-placeholder">
            <h3>📁 No Backups Yet</h3>
            <p>Create your first backup using the form on the left</p>
        </div>
        <?php endif; ?>
    </div>
</div>

Backup Manager - Good
Backup Manager – Good

<?php

// Get the backup directory and files

$backup_dir = ‘/tmp/backups/’;

$files = [];

$total_size = 0;

$file_count = 0;

if (is_dir($backup_dir)) {

    $all_files = scandir($backup_dir);

    foreach ($all_files as $file) {

        if ($file !== ‘.’ && $file !== ‘..’) {

            $file_path = $backup_dir . $file;

            $file_size = filesize($file_path);

            $files[] = [

                ‘name’ => $file,

                ‘path’ => $file_path,

                ‘size’ => $file_size,

                ‘modified’ => filemtime($file_path),

                ‘extension’ => pathinfo($file, PATHINFO_EXTENSION)

            ];

            $total_size += $file_size;

            $file_count++;

        }

    }

    // Sort by modification time (newest first)

    usort($files, function($a, $b) {

        return $b[‘modified’] – $a[‘modified’];

    });

}

// Handle delete all request

$delete_status = ”;

if ($_SERVER[‘REQUEST_METHOD’] === ‘POST’ && isset($_POST[‘delete_all’])) {

    $delete_status = ‘error’;

    $confirmed = $_POST[‘confirmation’] ?? ”;

    if ($confirmed === ‘DELETE’) {

        $deleted_count = 0;

        $errors = [];

        foreach ($files as $file) {

            if (unlink($file[‘path’])) {

                $deleted_count++;

            } else {

                $errors[] = “Could not delete: ” . $file[‘name’];

            }

        }

        if ($deleted_count > 0) {

            $delete_status = ‘success’;

            // Refresh page to show updated file list

            echo ‘<script>setTimeout(function(){ window.location.reload(); }, 2000);</script>’;

        }

        if (!empty($errors)) {

            $delete_status = ‘partial’;

        }

    } else {

        $delete_status = ‘confirm_error’;

    }

}

// Handle individual file deletion

if (isset($_GET[‘delete_file’])) {

    $file_to_delete = $_GET[‘delete_file’];

    if (file_exists($file_to_delete) && strpos(realpath($file_to_delete), realpath($backup_dir)) === 0) {

        if (unlink($file_to_delete)) {

            $delete_status = ‘success’;

            echo ‘<script>setTimeout(function(){ window.location.href = “?”; }, 1000);</script>’;

        } else {

            $delete_status = ‘error’;

        }

    }

}

?>

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>Backup File Manager</title>

    <link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css”>

    <style>

        :root {

            –primary: #4361ee;

            –success: #4cc9f0;

            –danger: #f72585;

            –warning: #f8961e;

            –dark: #2b2d42;

            –light: #f8f9fa;

            –gray: #6c757d;

            –border: #dee2e6;

        }

        * {

            box-sizing: border-box;

            margin: 0;

            padding: 0;

        }

        body {

            font-family: ‘Segoe UI’, Tahoma, Geneva, Verdana, sans-serif;

            line-height: 1.6;

            color: #333;

            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

            min-height: 100vh;

            padding: 20px;

        }

        .container {

            max-width: 1200px;

            margin: 0 auto;

            background: white;

            border-radius: 12px;

            box-shadow: 0 10px 30px rgba(0,0,0,0.15);

            overflow: hidden;

        }

        .header {

            background: var(–dark);

            color: white;

            padding: 25px;

            display: flex;

            justify-content: space-between;

            align-items: center;

            flex-wrap: wrap;

            gap: 15px;

        }

        .header h1 {

            font-size: 1.8rem;

            display: flex;

            align-items: center;

            gap: 10px;

        }

        .stats {

            display: flex;

            gap: 20px;

            background: rgba(255,255,255,0.1);

            padding: 12px 20px;

            border-radius: 8px;

        }

        .stat-item {

            display: flex;

            flex-direction: column;

            align-items: center;

        }

        .stat-value {

            font-size: 1.2rem;

            font-weight: bold;

        }

        .stat-label {

            font-size: 0.85rem;

            opacity: 0.8;

        }

        .content {

            padding: 25px;

        }

        .toolbar {

            display: flex;

            justify-content: space-between;

            align-items: center;

            margin-bottom: 25px;

            flex-wrap: wrap;

            gap: 15px;

        }

        .path-display {

            background: var(–light);

            padding: 12px 15px;

            border-radius: 8px;

            font-family: monospace;

            display: flex;

            align-items: center;

            gap: 10px;

        }

        .btn {

            padding: 12px 20px;

            border: none;

            border-radius: 8px;

            font-weight: 600;

            cursor: pointer;

            transition: all 0.3s ease;

            display: inline-flex;

            align-items: center;

            gap: 8px;

        }

        .btn-danger {

            background: var(–danger);

            color: white;

        }

        .btn-danger:hover {

            background: #e50c67;

            transform: translateY(-2px);

            box-shadow: 0 5px 15px rgba(247, 37, 133, 0.3);

        }

        .btn:disabled {

            opacity: 0.6;

            cursor: not-allowed;

            transform: none !important;

        }

        .files-container {

            display: grid;

            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));

            gap: 20px;

        }

        .file-card {

            background: white;

            border-radius: 10px;

            box-shadow: 0 4px 12px rgba(0,0,0,0.08);

            overflow: hidden;

            transition: transform 0.3s ease, box-shadow 0.3s ease;

            border: 1px solid var(–border);

            position: relative;

        }

        .file-card:hover {

            transform: translateY(-5px);

            box-shadow: 0 8px 20px rgba(0,0,0,0.12);

        }

        .file-header {

            padding: 15px;

            background: var(–light);

            display: flex;

            justify-content: space-between;

            align-items: center;

        }

        .file-icon {

            font-size: 1.8rem;

        }

        .sql-icon {

            color: #336791;

        }

        .zip-icon {

            color: #ff6b35;

        }

        .file-actions {

            display: flex;

            gap: 8px;

        }

        .action-btn {

            padding: 6px 10px;

            border-radius: 6px;

            background: white;

            border: 1px solid var(–border);

            cursor: pointer;

            transition: all 0.2s ease;

        }

        .delete-btn {

            color: var(–danger);

        }

        .delete-btn:hover {

            background: var(–danger);

            color: white;

        }

        .file-body {

            padding: 15px;

        }

        .file-name {

            font-weight: 600;

            margin-bottom: 10px;

            word-break: break-all;

        }

        .file-details {

            display: flex;

            justify-content: space-between;

            color: var(–gray);

            font-size: 0.85rem;

        }

        .empty-state {

            grid-column: 1 / -1;

            text-align: center;

            padding: 60px 20px;

            color: var(–gray);

        }

        .empty-state i {

            font-size: 3rem;

            margin-bottom: 15px;

            opacity: 0.5;

        }

        .modal {

            position: fixed;

            top: 0;

            left: 0;

            right: 0;

            bottom: 0;

            background: rgba(0,0,0,0.7);

            display: flex;

            justify-content: center;

            align-items: center;

            z-index: 1000;

            opacity: 0;

            pointer-events: none;

            transition: opacity 0.3s ease;

        }

        .modal.active {

            opacity: 1;

            pointer-events: all;

        }

        .modal-content {

            background: white;

            padding: 30px;

            border-radius: 12px;

            width: 90%;

            max-width: 500px;

            box-shadow: 0 20px 40px rgba(0,0,0,0.2);

            transform: translateY(20px);

            transition: transform 0.3s ease;

        }

        .modal.active .modal-content {

            transform: translateY(0);

        }

        .modal-header {

            margin-bottom: 20px;

            text-align: center;

        }

        .modal-icon {

            font-size: 3rem;

            color: var(–danger);

            margin-bottom: 15px;

        }

        .modal-body {

            margin-bottom: 25px;

        }

        .confirmation-input {

            width: 100%;

            padding: 12px 15px;

            border: 2px solid var(–border);

            border-radius: 8px;

            font-size: 16px;

            margin-top: 10px;

            text-align: center;

            letter-spacing: 1px;

            font-weight: 600;

        }

        .confirmation-input:focus {

            outline: none;

            border-color: var(–danger);

        }

        .modal-footer {

            display: flex;

            gap: 15px;

            justify-content: center;

        }

        .btn-cancel {

            background: var(–light);

            color: var(–dark);

        }

        .btn-cancel:hover {

            background: #e9ecef;

        }

        .alert {

            padding: 15px 20px;

            border-radius: 8px;

            margin-bottom: 25px;

            display: flex;

            align-items: center;

            gap: 12px;

        }

        .alert-success {

            background: #d4edda;

            color: #155724;

            border-left: 4px solid #28a745;

        }

        .alert-error {

            background: #f8d7da;

            color: #721c24;

            border-left: 4px solid #dc3545;

        }

        .alert-partial {

            background: #fff3cd;

            color: #856404;

            border-left: 4px solid #ffc107;

        }

        @media (max-width: 768px) {

            .header {

                flex-direction: column;

                text-align: center;

            }

            .stats {

                width: 100%;

                justify-content: center;

            }

            .toolbar {

                flex-direction: column;

            }

            .path-display {

                width: 100%;

                justify-content: center;

            }

            .files-container {

                grid-template-columns: 1fr;

            }

        }

        @keyframes fadeIn {

            from { opacity: 0; transform: translateY(20px); }

            to { opacity: 1; transform: translateY(0); }

        }

        .fade-in {

            animation: fadeIn 0.5s ease-out;

        }

        .file-age {

            position: absolute;

            top: 10px;

            right: 10px;

            background: rgba(0,0,0,0.7);

            color: white;

            padding: 4px 8px;

            border-radius: 4px;

            font-size: 0.75rem;

        }

    </style>

</head>

<body>

    <div class=”container fade-in”>

        <div class=”header”>

            <h1><i class=”fas fa-database”></i> Backup File Manager</h1>

            <div class=”stats”>

                <div class=”stat-item”>

                    <div class=”stat-value”><?php echo $file_count; ?></div>

                    <div class=”stat-label”>Files</div>

                </div>

                <div class=”stat-item”>

                    <div class=”stat-value”><?php echo format_size($total_size); ?></div>

                    <div class=”stat-label”>Total Size</div>

                </div>

            </div>

        </div>

        <div class=”content”>

            <?php if ($delete_status === ‘success’): ?>

                <div class=”alert alert-success”>

                    <i class=”fas fa-check-circle”></i>

                    <div>Files have been successfully deleted.</div>

                </div>

            <?php elseif ($delete_status === ‘error’ || $delete_status === ‘confirm_error’): ?>

                <div class=”alert alert-error”>

                    <i class=”fas fa-exclamation-circle”></i>

                    <div>

                        <?php

                        if ($delete_status === ‘confirm_error’) {

                            echo “Confirmation text was incorrect. No files were deleted.”;

                        } else {

                            echo “There was an error deleting some files.”;

                        }

                        ?>

                    </div>

                </div>

            <?php elseif ($delete_status === ‘partial’): ?>

                <div class=”alert alert-partial”>

                    <i class=”fas fa-exclamation-triangle”></i>

                    <div>Some files could not be deleted. Please check file permissions.</div>

                </div>

            <?php endif; ?>

            <div class=”toolbar”>

                <div class=”path-display”>

                    <i class=”fas fa-folder”></i>

                    <span><?php echo realpath($backup_dir); ?></span>

                </div>

                <?php if ($file_count > 0): ?>

                <button class=”btn btn-danger” onclick=”openModal()”>

                    <i class=”fas fa-trash-alt”></i> Delete All Files

                </button>

                <?php endif; ?>

            </div>

            <div class=”files-container”>

                <?php if ($file_count > 0): ?>

                    <?php foreach ($files as $file):

                        $file_age = time() – $file[‘modified’];

                        $age_text = ”;

                        if ($file_age < 3600) {

                            $age_text = floor($file_age / 60) . ‘m ago’;

                        } elseif ($file_age < 86400) {

                            $age_text = floor($file_age / 3600) . ‘h ago’;

                        } else {

                            $age_text = floor($file_age / 86400) . ‘d ago’;

                        }

                    ?>

                    <div class=”file-card”>

                        <span class=”file-age”><?php echo $age_text; ?></span>

                        <div class=”file-header”>

                            <div class=”file-icon”>

                                <?php if ($file[‘extension’] === ‘sql’): ?>

                                    <i class=”fas fa-database sql-icon”></i>

                                <?php elseif ($file[‘extension’] === ‘zip’): ?>

                                    <i class=”fas fa-file-archive zip-icon”></i>

                                <?php else: ?>

                                    <i class=”fas fa-file”></i>

                                <?php endif; ?>

                            </div>

                            <div class=”file-actions”>

                                <a href=”?delete_file=<?php echo urlencode($file[‘path’]); ?>”

                                   class=”action-btn delete-btn” title=”Delete”

                                   onclick=”return confirm(‘Are you sure you want to delete <?php echo htmlspecialchars($file[‘name’]); ?>?’)”>

                                    <i class=”fas fa-trash-alt”></i>

                                </a>

                            </div>

                        </div>

                        <div class=”file-body”>

                            <div class=”file-name”><?php echo htmlspecialchars($file[‘name’]); ?></div>

                            <div class=”file-details”>

                                <span><?php echo format_size($file[‘size’]); ?></span>

                                <span><?php echo date(‘Y-m-d H:i’, $file[‘modified’]); ?></span>

                            </div>

                        </div>

                    </div>

                    <?php endforeach; ?>

                <?php else: ?>

                    <div class=”empty-state”>

                        <i class=”fas fa-folder-open”></i>

                        <h3>No Backup Files Found</h3>

                        <p>The backup directory is empty. No files to manage.</p>

                    </div>

                <?php endif; ?>

            </div>

        </div>

    </div>

    <!– Delete Confirmation Modal –>

    <div class=”modal” id=”deleteModal”>

        <div class=”modal-content”>

            <div class=”modal-header”>

                <div class=”modal-icon”>

                    <i class=”fas fa-exclamation-triangle”></i>

                </div>

                <h2>Delete All Backup Files?</h2>

            </div>

            <div class=”modal-body”>

                <p>This action will permanently delete <strong><?php echo $file_count; ?> files</strong> (<?php echo format_size($total_size); ?>).</p>

                <p>This cannot be undone. Please type <strong>DELETE</strong> to confirm.</p>

                <form id=”deleteForm” method=”post” action=””>

                    <input type=”hidden” name=”delete_all” value=”1″>

                    <input type=”text” name=”confirmation” class=”confirmation-input”

                           placeholder=”Type DELETE here” required autocomplete=”off”>

                </form>

            </div>

            <div class=”modal-footer”>

                <button class=”btn btn-cancel” onclick=”closeModal()”>Cancel</button>

                <button class=”btn btn-danger” onclick=”confirmDelete()” disabled>

                    <i class=”fas fa-trash-alt”></i> Delete All

                </button>

            </div>

        </div>

    </div>

    <script>

        const modal = document.getElementById(‘deleteModal’);

        const confirmationInput = document.querySelector(‘input[name=”confirmation”]’);

        const deleteButton = document.querySelector(‘.modal-footer .btn-danger’);

        function openModal() {

            modal.classList.add(‘active’);

            confirmationInput.focus();

        }

        function closeModal() {

            modal.classList.remove(‘active’);

            confirmationInput.value = ”;

            deleteButton.disabled = true;

        }

        function confirmDelete() {

            document.getElementById(‘deleteForm’).submit();

        }

        // Enable delete button only when user types “DELETE”

        confirmationInput.addEventListener(‘input’, function() {

            deleteButton.disabled = this.value !== ‘DELETE’;

        });

        // Close modal when clicking outside

        modal.addEventListener(‘click’, function(e) {

            if (e.target === modal) {

                closeModal();

            }

        });

        // Close modal with Escape key

        document.addEventListener(‘keydown’, function(e) {

            if (e.key === ‘Escape’ && modal.classList.contains(‘active’)) {

                closeModal();

            }

        });

    </script>

</body>

</html>

<?php

// Helper function to format file sizes

function format_size($bytes) {

    if ($bytes == 0) return ‘0 B’;

    $sizes = [‘B’, ‘KB’, ‘MB’, ‘GB’];

    $i = floor(log($bytes, 1024));

    return round($bytes / pow(1024, $i), 2) . ‘ ‘ . $sizes[$i];

}

?>

DB Monitor SS-01
DB Monitor SS-01
DB Monitor SS-02
DB Monitor SS-02
<?php
// tool_monitor.php - Database Monitoring Tool
$root_password = $_SESSION['mysql_root_password'] ?? '';

if (empty($root_password)) {
    echo '<div class="error fade-in">Please login first to access monitoring tools.</div>';
    return;
}

// Auto-refresh setting (default: 30 seconds)
$refresh_interval = isset($_GET['refresh']) ? intval($_GET['refresh']) : 30;
if ($refresh_interval < 5) $refresh_interval = 5; // Minimum 5 seconds
if ($refresh_interval > 300) $refresh_interval = 300; // Maximum 5 minutes

try {
    // Connect to MySQL using PDO
    $pdo = new PDO("mysql:host=localhost", 'root', $root_password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Get all databases using SHOW DATABASES (more reliable)
    $databases_result = $pdo->query("SHOW DATABASES");
    $all_databases = $databases_result->fetchAll(PDO::FETCH_COLUMN);
    
    // Filter out system databases
    $system_databases = ['information_schema', 'mysql', 'performance_schema', 'sys', 'phpmyadmin'];
    $user_databases = array_diff($all_databases, $system_databases);
    
    // Get details for each user database
    $database_details = [];
    foreach ($user_databases as $db_name) {
        try {
            $stmt = $pdo->prepare("
                SELECT 
                    ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) as size_mb,
                    COUNT(table_name) as table_count,
                    GROUP_CONCAT(DISTINCT engine ORDER BY engine SEPARATOR ', ') as engines
                FROM information_schema.tables 
                WHERE table_schema = ?
            ");
            $stmt->execute([$db_name]);
            $db_info = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($db_info) {
                $database_details[] = [
                    'Database' => $db_name,
                    'Size (MB)' => $db_info['size_mb'] ?? '0.00',
                    'Tables' => $db_info['table_count'] ?? '0',
                    'Engines' => $db_info['engines'] ?? 'N/A'
                ];
            } else {
                // Database exists but has no tables
                $database_details[] = [
                    'Database' => $db_name,
                    'Size (MB)' => '0.00',
                    'Tables' => '0',
                    'Engines' => 'N/A'
                ];
            }
        } catch (Exception $e) {
            // If we can't get details, just show the database name
            $database_details[] = [
                'Database' => $db_name,
                'Size (MB)' => 'N/A',
                'Tables' => 'N/A',
                'Engines' => 'N/A'
            ];
        }
    }
    
    // Sort by database name
    usort($database_details, function($a, $b) {
        return strcmp($a['Database'], $b['Database']);
    });
    
    // Get user list with privileges - Filter out system users
    $users = $pdo->query("
        SELECT 
            User, 
            Host,
            Grant_priv,
            max_connections as 'Max Connections',
            max_user_connections as 'Max User Connections'
        FROM mysql.user 
        WHERE User NOT IN ('debian-sys-maint', 'phpmyadmin', 'root', 'mysql.sys', 'mysql.session', 'mysql.infoschema') 
        ORDER BY User, Host
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    // Get server status
    $status_result = $pdo->query("SHOW GLOBAL STATUS");
    $status = [];
    if ($status_result) {
        $status = $status_result->fetchAll(PDO::FETCH_KEY_PAIR);
    }
    
    // Get server variables
    $variables_result = $pdo->query("SHOW GLOBAL VARIABLES");
    $variables = [];
    if ($variables_result) {
        $variables = $variables_result->fetchAll(PDO::FETCH_KEY_PAIR);
    }
    
    // Get process list
    $processes_result = $pdo->query("SHOW PROCESSLIST");
    $processes = [];
    if ($processes_result) {
        $processes = $processes_result->fetchAll(PDO::FETCH_ASSOC);
    }
    
    // Calculate some useful metrics
    $uptime = isset($status['Uptime']) ? gmdate("H:i:s", $status['Uptime']) : 'N/A';
    $qps = (isset($status['Questions']) && isset($status['Uptime']) && $status['Uptime'] > 0) ? 
        round($status['Questions'] / $status['Uptime'], 2) : 0;
    
    $connections_usage = 0;
    if (isset($status['Threads_connected']) && isset($variables['max_connections']) && $variables['max_connections'] > 0) {
        $connections_usage = round(($status['Threads_connected'] / $variables['max_connections']) * 100, 2);
    }
    
} catch (PDOException $e) {
    echo '<div class="error fade-in">❌ Error connecting to MySQL: ' . $e->getMessage() . '</div>';
    return;
}
?>

<!-- Auto-refresh control -->
<div style="background: #e9ecef; padding: 15px; border-radius: 8px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
    <div>
        <strong>Auto-Refresh:</strong> 
        <span id="refresh-countdown"><?php echo $refresh_interval; ?></span> seconds
    </div>
    <div>
        <form method="get" style="display: inline-block; margin-right: 10px;">
            <input type="hidden" name="tool" value="monitor">
            <label for="refresh-interval">Refresh every:</label>
            <select name="refresh" id="refresh-interval" onchange="this.form.submit()" style="padding: 5px; border-radius: 4px;">
                <option value="10" <?php echo $refresh_interval == 10 ? 'selected' : ''; ?>>10 seconds</option>
                <option value="30" <?php echo $refresh_interval == 30 ? 'selected' : ''; ?>>30 seconds</option>
                <option value="60" <?php echo $refresh_interval == 60 ? 'selected' : ''; ?>>1 minute</option>
                <option value="300" <?php echo $refresh_interval == 300 ? 'selected' : ''; ?>>5 minutes</option>
                <option value="0" <?php echo $refresh_interval == 0 ? 'selected' : ''; ?>>Off</option>
            </select>
        </form>
        <button onclick="refreshNow()" style="background: #4361ee; color: white; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer;">🔄 Refresh Now</button>
    </div>
</div>

<div class="monitor-container">
    <!-- Server Status Overview -->
    <div class="status-cards" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 30px;">
        <div class="status-card" style="background: linear-gradient(135deg, #4361ee, #3a0ca3); color: white; padding: 20px; border-radius: 10px; text-align: center;">
            <div style="font-size: 2em; margin-bottom: 10px;"><?php echo count($database_details); ?></div>
            <div>Databases</div>
        </div>
        
        <div class="status-card" style="background: linear-gradient(135deg, #f72585, #b5179e); color: white; padding: 20px; border-radius: 10px; text-align: center;">
            <div style="font-size: 2em; margin-bottom: 10px;"><?php echo count($users); ?></div>
            <div>Users</div>
        </div>
        
        <div class="status-card" style="background: linear-gradient(135deg, #4cc9f0, #4895ef); color: white; padding: 20px; border-radius: 10px; text-align: center;">
            <div style="font-size: 2em; margin-bottom: 10px;"><?php echo $uptime; ?></div>
            <div>Uptime</div>
        </div>
        
        <div class="status-card" style="background: linear-gradient(135deg, #f8961e, #f3722c); color: white; padding: 20px; border-radius: 10px; text-align: center;">
            <div style="font-size: 2em; margin-bottom: 10px;"><?php echo $qps; ?></div>
            <div>Queries/Sec</div>
        </div>
        
        <div class="status-card" style="background: linear-gradient(135deg, #90be6d, #43aa8b); color: white; padding: 20px; border-radius: 10px; text-align: center;">
            <div style="font-size: 2em; margin-bottom: 10px;"><?php echo $connections_usage; ?>%</div>
            <div>Connections</div>
        </div>
    </div>

    <!-- Database List -->
    <div class="card" style="background: white; border-radius: 10px; padding: 25px; margin-bottom: 30px; box-shadow: 0 5px 15px rgba(0,0,0,0.08);">
        <h3 style="margin-bottom: 20px; color: #4361ee; display: flex; align-items: center; gap: 10px;">
            <span style="font-size: 1.2em;">🗄️</span> Databases (<?php echo count($database_details); ?>)
        </h3>
        
        <?php if (!empty($database_details)): ?>
        <div style="overflow-x: auto;">
            <table style="width: 100%; border-collapse: collapse;">
                <thead>
                    <tr style="background: #f8f9fa;">
                        <th style="padding: 12px; text-align: left; border-bottom: 2px solid #dee2e6;">Database</th>
                        <th style="padding: 12px; text-align: right; border-bottom: 2px solid #dee2e6;">Size (MB)</th>
                        <th style="padding: 12px; text-align: center; border-bottom: 2px solid #dee2e6;">Tables</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 2px solid #dee2e6;">Engines</th>
                        <th style="padding: 12px; text-align: center; border-bottom: 2px solid #dee2e6;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($database_details as $index => $db): ?>
                    <tr style="background: <?php echo $index % 2 === 0 ? '#fff' : '#f8f9fa'; ?>;">
                        <td style="padding: 12px; border-bottom: 1px solid #dee2e6; font-weight: 600;"><?php echo htmlspecialchars($db['Database']); ?></td>
                        <td style="padding: 12px; border-bottom: 1px solid #dee2e6; text-align: right;"><?php echo $db['Size (MB)']; ?></td>
                        <td style="padding: 12px; border-bottom: 1px solid #dee2e6; text-align: center;"><?php echo $db['Tables']; ?></td>
                        <td style="padding: 12px; border-bottom: 1px solid #dee2e6;"><?php echo $db['Engines'] ?? 'N/A'; ?></td>
                        <td style="padding: 12px; border-bottom: 1px solid #dee2e6; text-align: center;">
                            <a href="?tool=backup&db_name=<?php echo urlencode($db['Database']); ?>" 
                               style="background: #4361ee; color: white; padding: 6px 12px; border-radius: 4px; text-decoration: none; display: inline-block; margin: 2px;"
                               title="Backup this database">💾</a>
                            <a href="?tool=drop&db_name=<?php echo urlencode($db['Database']); ?>" 
                               style="background: #f72585; color: white; padding: 6px 12px; border-radius: 4px; text-decoration: none; display: inline-block; margin: 2px;"
                               title="Drop this database" 
                               onclick="return confirm('Are you sure you want to drop database <?php echo htmlspecialchars($db['Database']); ?>? This cannot be undone!')">🗑️</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php else: ?>
        <div style="text-align: center; padding: 40px; color: #6c757d;">
            <div style="font-size: 3em; margin-bottom: 15px; opacity: 0.5;">🗄️</div>
            <h4>No User Databases Found</h4>
            <p>No user databases exist on this MySQL server. System databases are hidden for safety.</p>
        </div>
        <?php endif; ?>
    </div>

    <!-- User List -->
    <div class="card" style="background: white; border-radius: 10px; padding: 25px; margin-bottom: 30px; box-shadow: 0 5px 15px rgba(0,0,0,0.08);">
        <h3 style="margin-bottom: 20px; color: #4361ee; display: flex; align-items: center; gap: 10px;">
            <span style="font-size: 1.2em;">👥</span> Users (<?php echo count($users); ?>)
        </h3>
        
        <?php if (!empty($users)): ?>
        <div style="overflow-x: auto;">
            <table style="width: 100%; border-collapse: collapse;">
                <thead>
                    <tr style="background: #f8f9fa;">
                        <th style="padding: 12px; text-align: left; border-bottom: 2px solid #dee2e6;">User</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 2px solid #dee2e6;">Host</th>
                        <th style="padding: 12px; text-align: center; border-bottom: 2px solid #dee2e6;">Grant Privilege</th>
                        <th style="padding: 12px; text-align: center; border-bottom: 2px solid #dee2e6;">Max Connections</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $index => $user): ?>
                    <tr style="background: <?php echo $index % 2 === 0 ? '#fff' : '#f8f9fa'; ?>;">
                        <td style="padding: 12px; border-bottom: 1px solid #dee2e6; font-weight: 600;"><?php echo htmlspecialchars($user['User']); ?></td>
                        <td style="padding: 12px; border-bottom: 1px solid #dee2e6;"><?php echo htmlspecialchars($user['Host']); ?></td>
                        <td style="padding: 12px; border-bottom: 1px solid #dee2e6; text-align: center;">
                            <span style="background: <?php echo $user['Grant_priv'] === 'Y' ? '#4cc9f0' : '#f8961e'; ?>; color: white; padding: 4px 8px; border-radius: 12px; font-size: 0.85em;">
                                <?php echo $user['Grant_priv'] === 'Y' ? 'Yes' : 'No'; ?>
                            </span>
                        </td>
                        <td style="padding: 12px; border-bottom: 1px solid #dee2e6; text-align: center;">
                            <?php echo $user['Max User Connections'] ?: ($user['Max Connections'] ?: 'Unlimited'); ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php else: ?>
        <div style="text-align: center; padding: 40px; color: #6c757d;">
            <div style="font-size: 3em; margin-bottom: 15px; opacity: 0.5;">👥</div>
            <h4>No User Accounts Found</h4>
            <p>No user accounts exist on this MySQL server. System users are hidden for safety.</p>
        </div>
        <?php endif; ?>
    </div>

    <!-- Performance Metrics -->
    <div class="card" style="background: white; border-radius: 10px; padding: 25px; margin-bottom: 30px; box-shadow: 0 5px 15px rgba(0,0,0,0.08);">
        <h3 style="margin-bottom: 20px; color: #4361ee; display: flex; align-items: center; gap: 10px;">
            <span style="font-size: 1.2em;">📊</span> Performance Metrics
        </h3>
        
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">
            <!-- Connection Metrics -->
            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px;">
                <h4 style="margin-bottom: 15px; color: #4361ee;">Connections</h4>
                <div style="margin-bottom: 10px; display: flex; justify-content: space-between;">
                    <span>Max Connections:</span>
                    <strong><?php echo $variables['max_connections'] ?? 'N/A'; ?></strong>
                </div>
                <div style="margin-bottom: 10px; display: flex; justify-content: space-between;">
                    <span>Current Connections:</span>
                    <strong><?php echo $status['Threads_connected'] ?? 'N/A'; ?></strong>
                </div>
                <div style="margin-bottom: 10px; display: flex; justify-content: space-between;">
                    <span>Running Threads:</span>
                    <strong><?php echo $status['Threads_running'] ?? 'N/A'; ?></strong>
                </div>
                <div style="background: #e9ecef; height: 20px; border-radius: 10px; margin-top: 10px; overflow: hidden;">
                    <div style="background: #4361ee; height: 100%; width: <?php echo min($connections_usage, 100); ?>%;"></div>
                </div>
            </div>
            
            <!-- Query Metrics -->
            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px;">
                <h4 style="margin-bottom: 15px; color: #4361ee;">Query Statistics</h4>
                <div style="margin-bottom: 10px; display: flex; justify-content: space-between;">
                    <span>Queries per Second:</span>
                    <strong><?php echo $qps; ?></strong>
                </div>
                <div style="margin-bottom: 10px; display: flex; justify-content: space-between;">
                    <span>Slow Queries:</span>
                    <strong><?php echo $status['Slow_queries'] ?? '0'; ?></strong>
                </div>
                <div style="margin-bottom: 10px; display: flex; justify-content: space-between;">
                    <span>Select Queries:</span>
                    <strong><?php echo $status['Com_select'] ?? '0'; ?></strong>
                </div>
                <div style="margin-bottom: 10px; display: flex; justify-content: space-between;">
                    <span>Update Queries:</span>
                    <strong><?php echo $status['Com_update'] ?? '0'; ?></strong>
                </div>
            </div>
            
            <!-- Buffer Metrics -->
            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px;">
                <h4 style="margin-bottom: 15px; color: #4361ee;">Buffer & Cache</h4>
                <div style="margin-bottom: 10px; display: flex; justify-content: space-between;">
                    <span>Key Buffer Size:</span>
                    <strong><?php echo isset($variables['key_buffer_size']) ? round($variables['key_buffer_size'] / 1024 / 1024, 2) : 'N/A'; ?> MB</strong>
                </div>
                <div style="margin-bottom: 10px; display: flex; justify-content: space-between;">
                    <span>Query Cache Size:</span>
                    <strong><?php echo isset($variables['query_cache_size']) ? round($variables['query_cache_size'] / 1024 / 1024, 2) : 'N/A'; ?> MB</strong>
                </div>
                <div style="margin-bottom: 10px; display: flex; justify-content: space-between;">
                    <span>InnoDB Buffer Pool:</span>
                    <strong><?php echo isset($variables['innodb_buffer_pool_size']) ? round($variables['innodb_buffer_pool_size'] / 1024 / 1024, 2) : 'N/A'; ?> MB</strong>
                </div>
            </div>
        </div>
    </div>

    <!-- Active Processes -->
    <div class="card" style="background: white; border-radius: 10px; padding: 25px; box-shadow: 0 5px 15px rgba(0,0,0,0.08);">
        <h3 style="margin-bottom: 20px; color: #4361ee; display: flex; align-items: center; gap: 10px;">
            <span style="font-size: 1.2em;">🔍</span> Active Processes (<?php echo count($processes); ?>)
        </h3>
        
        <?php if (!empty($processes)): ?>
        <div style="overflow-x: auto; max-height: 400px;">
            <table style="width: 100%; border-collapse: collapse;">
                <thead style="position: sticky; top: 0; z-index: 10;">
                    <tr style="background: #f8f9fa;">
                        <th style="padding: 12px; text-align: left; border-bottom: 2px solid #dee2e6;">ID</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 2px solid #dee2e6;">User</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 2px solid #dee2e6;">Host</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 2px solid #dee2e6;">Database</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 2px solid #dee2e6;">Command</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 2px solid #dee2e6;">Time</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 2px solid #dee2e6;">State</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 2px solid #dee2e6;">Info</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($processes as $index => $process): ?>
                    <tr style="background: <?php echo $index % 2 === 0 ? '#fff' : '#f8f9fa'; ?>;">
                        <td style="padding: 8px; border-bottom: 1px solid #dee2e6;"><?php echo $process['Id']; ?></td>
                        <td style="padding: 8px; border-bottom: 1px solid #dee2e6;"><?php echo htmlspecialchars($process['User']); ?></td>
                        <td style="padding: 8px; border-bottom: 1px solid #dee2e6;"><?php echo htmlspecialchars($process['Host']); ?></td>
                        <td style="padding: 8px; border-bottom: 1px solid #dee2e6;"><?php echo htmlspecialchars($process['db'] ?? 'N/A'); ?></td>
                        <td style="padding: 8px; border-bottom: 1px solid #dee2e6;"><?php echo htmlspecialchars($process['Command']); ?></td>
                        <td style="padding: 8px; border-bottom: 1px solid #dee2e6;"><?php echo $process['Time']; ?>s</td>
                        <td style="padding: 8px; border-bottom: 1px solid #dee2e6;"><?php echo htmlspecialchars($process['State'] ?? 'N/A'); ?></td>
                        <td style="padding: 8px; border-bottom: 1px solid #dee2e6; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                            <?php echo htmlspecialchars($process['Info'] ?? 'N/A'); ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php else: ?>
        <div style="text-align: center; padding: 40px; color: #6c757d;">
            <div style="font-size: 3em; margin-bottom: 15px; opacity: 0.5;">🔍</div>
            <h4>No Active Processes</h4>
            <p>No database processes are currently running.</p>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
// Auto-refresh functionality
let refreshInterval = <?php echo $refresh_interval; ?>;
let countdown = refreshInterval;

function startRefreshCountdown() {
    if (refreshInterval > 0) {
        const countdownElement = document.getElementById('refresh-countdown');
        if (countdownElement) {
            countdownElement.textContent = countdown;
        }
        
        if (countdown <= 0) {
            window.location.reload();
        } else {
            countdown--;
            setTimeout(startRefreshCountdown, 1000);
        }
    }
}

function refreshNow() {
    window.location.reload();
}

// Start the countdown when page loads
if (refreshInterval > 0) {
    setTimeout(startRefreshCountdown, 1000);
}
</script>

<style>
.monitor-container {
    animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}

.status-card {
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.status-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0,0,0,0.15);
}

table {
    font-size: 0.9em;
}

th {
    font-weight: 600;
}

tr:hover {
    background-color: #f1f3f9 !important;
}
</style>

💡 Why This Toolkit?

This project was born out of a need for reproducible workflows and rookie-friendly tooling. Whether you’re onboarding a new contributor or managing a local dev server, this toolkit keeps things simple, secure, and scalable.

🔐 Security Notes

  • No password is stored persistently — only in session memory.
  • No external dependencies.
  • Ideal for local or semi-private deployments.

🧠 Learn More

Explore the source code on GitHub. Built with ❤️ by the IT-INDIA.org community.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

No Ads, No Buy Buttons! IT-INDIA.org