gdbackup

MySQL Backup for cPanel

A free, open-source tool to back up MySQL databases from cPanel (or a LAMP server) to local storage, Google Drive, or Telegram. Supports four modes: local storage, zip upload to Google Drive, direct streaming to Google Drive, or zip upload to Telegram. Multiple modes can be used simultaneously for flexible backups. Designed to be easy to use, maintain, and debug, with efficient multi-mode execution and detailed logging.

Features

Prerequisites

Installation

  1. Clone or Download:
    • Clone the repository: git clone https://github.com/dominusmmp/gdbackup.git
    • Or download and extract the ZIP file to your cPanel File Manager (e.g., /home/username/gdbackup).
  2. Set Permissions:
    • Ensure the script directory is writable: chmod 755 /path/to/gdbackup.
    • Protect sensitive files (config.php, .refresh-token.php, error.*.log) by placing them outside the web root or using .htaccess:
      <FilesMatch "^(config\.php|\.refresh-token\.php|error.*\.log)$">
          Deny from all
      </FilesMatch>
      
  3. Install Dependencies:
    • No external libraries are required; all dependencies are included in the src directory.

Configuration

The project includes a template configuration file, config.template.php, which you should copy and rename to config.php before customizing. Do not edit config.template.php directly, as it serves as a reference for the required settings. For Google Drive API authentication (for gd-upload or gd-stream modes), use auth.html to obtain the authorization code.

  1. Create config.php:
    • Copy config.template.php to config.php:
      cp config.template.php config.php
      
    • Open config.php in a text editor and fill in the required values as described below.
    • Ensure config.php is protected (e.g., chmod 600 config.php) and placed outside the web root or secured via .htaccess.
    • Validate Configuration: Before running the script, verify all fields in config.php are correctly filled to avoid runtime errors.

Security Configuration

General Configuration

Database Configuration

Google Drive API Configuration (for gd-upload or gd-stream modes)

  1. Create OAuth Credentials:
    • Go to Google Cloud Console.
    • Enable the Google Drive API.
    • Create an OAuth 2.0 Client ID (select “Web application”).
    • Add the redirect URI (e.g., http://yourdomain.com/auth.html or https://dominusmmp.github.io/gdbackup/auth.html) under “Authorized redirect URIs”.
    • Copy the Client ID and Client Secret.
  2. Obtain $authCode:
    • Use auth.html to generate the authorization code:
      • Option 1: Local Server: Use auth.html on your local web server (e.g., http://localhost/auth.html).
      • Option 2: Host Online: Upload auth.html to your web server (e.g., http://yourdomain.com/auth.html).
      • Option 3: Project GitHub Pages: Use the project’s GitHub Pages version: https://dominusmmp.github.io/gdbackup/auth.html.
      • Enter your Client ID, verify the redirect URI, and click “Generate Auth URL”.
      • Authenticate with Google, and you’ll be redirected to auth.html with your authCode displayed.
      • Copy the authCode and paste it into $authCode in config.php.
        $authCode = '4/0A...';
        
  3. Configure config.php:
    • $driveRootFolderId:
      • ID of the Google Drive folder for backups (optional; leave empty for root).
      • Find in the URL: https://drive.google.com/drive/folders/YourFolderID.
      • Example: '1aBcDeFgHiJkLmNoPqRsTuVwXyZ'.
    • $clientId:
      • OAuth Client ID (e.g., '1234567890-abcdefg.apps.googleusercontent.com').
    • $clientSecret:
      • OAuth Client Secret (e.g., 'GOCSPX-abcdefg1234567890').
    • $redirectUri:
      • URL of auth.html (e.g., http://yourdomain.com/auth.html or https://dominusmmp.github.io/gdbackup/auth.html).
    • $authCode:
      • Authorization code from step 2 (e.g., '4/0A...').
    • $encryptionPassword:
      • Strong password for refresh token encryption (e.g., 'StrongPassword123!').
    • $encryptionKey:
      • Key/UUID for encryption (generate at uuidgenerator.net).
      • Example: '550e8400-e29b-41d4-a716-446655440000'.
    • Note: The refresh token is stored in .refresh-token.php with the format <?php defined('GDBPATH') || die('forbidden'); // [timestamp] $encryptedToken. Protect this file (chmod 600) and back it up. If lost or corrupted, regenerate $authCode via auth.html.

Telegram API Configuration (for tg-upload mode)

  1. Create a Telegram Bot:
    • Open Telegram and start a chat with BotFather.
    • Send /newbot, follow the prompts to name your bot, and receive a Bot API token (e.g., 123456789:ABC-DEF1234ghIkl-zyx57W2v1u123ew11).
    • Copy the token for use in config.php.
  2. Set Up a Chat:
    • Choose a chat where the bot will send backups. The bot must have permission to send messages and upload files in the chosen chat. Supported chat types:
      • Private Chat: Use your personal chat with the bot. Start a conversation with the bot to initialize it.
      • Group/Supergroup: Add the bot to a group or supergroup and grant it administrator privileges (to send files).
      • Channel: Add the bot to a public or private channel as an administrator.
    • Obtain the Chat ID:
      • Option 1: Use a Bot: Send a message in the target chat (private, group, or channel), then use a bot like GetIDs Bot to retrieve the chat ID.
        • For private chats: You’ll get a positive integer (e.g., 123456789).
        • For public channels/groups/supergroups: You’ll get a negative integer (e.g., -123456789 or -100123456789).
        • For channels: You’ll get the channel username (e.g., @MyBackupChannel) or a negative integer (e.g., -100123456789).
      • Option 2: Channel Username: For public channels, use the channel’s username (e.g., @MyBackupChannel).
      • Option 3: Test with Bot: Send a message to the bot or chat, then use the Telegram API to retrieve updates:
        • Make an API call: https://api.telegram.org/bot<YourBotToken>/getUpdates.
        • Look for the chat object in the response to find the id or username.
  3. Configure config.php:
    • $telegramBotToken:
      • Paste the Bot API token from BotFather (e.g., '123456789:ABC-DEF1234ghIkl-zyx57W2v1u123ew11').
    • $telegramChatId:
      • Paste the chat ID or username based on the chat type:
        • Private chat: Positive integer (e.g., '123456789').
        • Private channel/group/supergroup: Negative integer (e.g., '-123456789' or '-100123456789').
        • Public channel: Username (e.g., '@MyBackupChannel') or negative integer (e.g., '-100123456789').
    • $telegramFileSizeLimit:
      • Maximum file size for uploads in bytes (default: 50000000 for 50MB).
      • For premium Telegram bots, set up to 2000000000 (2GB).
      • Example: 2000000000.

    Example configuration in config.php:

    $telegramBotToken = '123456789:ABC-DEF1234ghIkl-zyx57W2v1u123ew11';
    $telegramChatId = '@MyBackupChannel'; // Or '123456789' for private chat, '-100123456789' for group/channel
    $telegramFileSizeLimit = 50000000;
    

Usage

Manual Backup

Automated Backup (Cronjob)

  1. In cPanel, go to “Cron Jobs”.
  2. Add a new cronjob:
    /usr/local/bin/php /path/to/run.php your-cronjob-key
    
  3. Set the schedule (e.g., daily at midnight).

Backup Output

Database Restoration

The restore.php script restores a MySQL database from a .sql or .sql.gz backup file created by run.php. It supports both hardcoded configuration and interactive CLI prompts.

Manual Restoration

  1. Edit restore.php (optional):
    • Open restore.php and set the following variables at the top:
      $dbHost = 'localhost:3306'; // Database host
      $dbUsername = 'myuser'; // Database username
      $dbPassword = 'mypassword'; // Database password
      $dbName = 'mydatabase'; // Database to restore
      $backupFile = '/path/to/backup.sql.gz'; // Path to .sql or .sql.gz file
      
    • If left empty, the script will prompt for these values when run via CLI.
  2. Run the Script:
    • Via CLI (recommended):
      php /path/to/restore.php
      
      • If variables are not set, follow the interactive prompts to enter dbHost, dbUsername, dbPassword, dbName, and backupFile.
    • Via HTTP:
      • Access http://yourdomain.com/restore.php (requires variables to be set in the script).
      • Note: HTTP mode is less secure; use CLI for production environments.
  3. Output:
    • On success: Displays “Successfully restored database ‘dbname’ from backupFile”.
    • On failure: Displays an error message (e.g., invalid file, database connection failure).
    • Temporary decompressed files (for .sql.gz) are automatically deleted.

Restoration Notes

cPanel Tips

Troubleshooting

Project Structure

🗂️ gdbackup/
├── 📁 .logs/
│   └── error.Y-m-d.log
├── 📁 src/
│   ├── BackupController.php
│   ├── EncryptionHelper.php
│   ├── GoogleDriveAPI.php
│   ├── Logger.php
│   ├── MySQLBackupAPI.php
│   ├── TelegramAPI.php
│   └── ZipHelper.php
├── .gitignore
├── .htaccess
├── .refresh-token.php
├── auth.html
├── config.php
├── config.template.php
├── readme.md
├── restore.php
└── run.php

Acknowledgments

License

Licensed under the MIT License. See LICENSE for details.