PHPackages                             indiehd/mysql-db-backup - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. indiehd/mysql-db-backup

ActiveLibrary[Database &amp; ORM](/categories/database)

indiehd/mysql-db-backup
=======================

A CLI tool for automated MySQL/MariaDB database backups with intelligent deduplication and compression. Perfect for scheduled cron jobs.

v1.0.0(2mo ago)26GPL-3.0-or-laterPHPPHP &gt;=8.0

Since Feb 25Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/indiehd/mysql-db-backup)[ Packagist](https://packagist.org/packages/indiehd/mysql-db-backup)[ RSS](/packages/indiehd-mysql-db-backup/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (4)Used By (0)

MySQL Database Backup
=====================

[](#mysql-database-backup)

A PHP CLI tool for automated MySQL/MariaDB database backups with intelligent deduplication and compression.

Features
--------

[](#features)

- ✅ **Automated backups** of all databases (excluding system databases)
- ✅ **Intelligent deduplication** - skips backups if database content hasn't changed (SHA1 hash comparison)
- ✅ **Automatic compression** - gzip compression of backup files
- ✅ **Organized storage** - separate directories for each database
- ✅ **Cron-ready** - designed for scheduled execution
- ✅ **Docker support** - includes Dockerfile for containerized usage
- ✅ **Flexible configuration** - INI file or environment variables

Requirements
------------

[](#requirements)

- PHP 8.0 or higher (for native installation)
- `mysqli` PHP extension (for native installation)
- **Docker** (for containerized installation - recommended)
- MySQL or MariaDB server
- System executables: `mysqldump`, `gzip`, `gunzip`, `sha1sum` (included in Docker image)

### Docker Setup Prerequisites

[](#docker-setup-prerequisites)

If using Docker (recommended), ensure your user has Docker permissions:

```
# Add your user to the docker group
sudo usermod -aG docker your_username

# Log out and back in, or run:
newgrp docker

# Verify Docker access (should work without sudo)
docker ps
```

Database User Setup
-------------------

[](#database-user-setup)

### Choose Your Deployment Scenario

[](#choose-your-deployment-scenario)

Pick the option that matches your setup:

ScenarioUser SetupNetwork ModeBest For**A: Localhost MySQL**`'backup'@'localhost'``--network host`Single server, MySQL on localhost (simplest)**B: Isolated Container**`'backup'@'%'``bridge` (default)Better isolation, any Docker setup**C: Multi-Container**`'backup'@'%'`Custom networkMySQL in another container### Scenario A: Localhost MySQL (Recommended for Single Server)

[](#scenario-a-localhost-mysql-recommended-for-single-server)

**Best for:** MySQL/MariaDB running on the same server as Docker

```
-- Log in to MySQL/MariaDB as root
sudo mysql

-- Create backup user for localhost connections
CREATE USER 'backup'@'localhost' IDENTIFIED BY 'your_secure_password';

-- Grant necessary permissions for full database backups
GRANT SELECT, LOCK TABLES, SHOW VIEW, TRIGGER, EVENT ON *.* TO 'backup'@'localhost';
GRANT SELECT ON mysql.proc TO 'backup'@'localhost';

FLUSH PRIVILEGES;
EXIT;

-- Test it
mysql -u backup -p
```

**Configuration (.env):**

```
DOCKER_NETWORK_MODE=host
DB_HOST=127.0.0.1
DB_USERNAME=backup
DB_PASSWORD=your_secure_password
```

**Important:** Use `127.0.0.1`, NOT `localhost`! See `.env.example` for explanation.

**Security:** Most secure - only accepts connections from localhost

### Scenario B: Bridge Network (Better Isolation)

[](#scenario-b-bridge-network-better-isolation)

**Best for:** When you want container isolation or don't want to use `--network host`

```
sudo mysql

-- Create backup user that accepts connections from any IP
-- Still secure because it requires password and MySQL should be firewalled
CREATE USER 'backup'@'%' IDENTIFIED BY 'your_strong_password';

-- Or restrict to Docker networks only (more restrictive)
-- CREATE USER 'backup'@'172.%' IDENTIFIED BY 'your_strong_password';

GRANT SELECT, LOCK TABLES, SHOW VIEW, TRIGGER, EVENT ON *.* TO 'backup'@'%';
GRANT SELECT ON mysql.proc TO 'backup'@'%';

FLUSH PRIVILEGES;
EXIT;
```

**Configuration (.env):**

```
DOCKER_NETWORK_MODE=bridge
DB_HOST=172.17.0.1        # Docker bridge gateway (usually stable)
# Or on some systems: DB_HOST=host.docker.internal
DB_USERNAME=backup
DB_PASSWORD=your_strong_password
```

**Security:** Good - relies on password auth and firewall. Ensure MySQL is not exposed to internet!

### Scenario C: Multi-Container Setup

[](#scenario-c-multi-container-setup)

**Best for:** MySQL running in another Docker container

```
-- Same as Scenario B
CREATE USER 'backup'@'%' IDENTIFIED BY 'your_strong_password';
GRANT SELECT, LOCK TABLES, SHOW VIEW, TRIGGER, EVENT ON *.* TO 'backup'@'%';
GRANT SELECT ON mysql.proc TO 'backup'@'%';
FLUSH PRIVILEGES;
```

**Configuration (.env):**

```
DOCKER_NETWORK_MODE=your_mysql_network_name
DB_HOST=mysql_container_name  # Name of your MySQL container
DB_USERNAME=backup
DB_PASSWORD=your_strong_password
```

### Quick Reference: Permission Grants

[](#quick-reference-permission-grants)

The minimum permissions needed for backups:

```
-- Read all tables
GRANT SELECT ON *.* TO 'backup'@'...';

-- Lock tables during backup (for consistency)
GRANT LOCK TABLES ON *.* TO 'backup'@'...';

-- Backup views
GRANT SHOW VIEW ON *.* TO 'backup'@'...';

-- Backup triggers
GRANT TRIGGER ON *.* TO 'backup'@'...';

-- Backup events (scheduled tasks)
GRANT EVENT ON *.* TO 'backup'@'...';

-- Backup stored procedures/functions
GRANT SELECT ON mysql.proc TO 'backup'@'...';
```

Quick Start (Docker - Recommended)
----------------------------------

[](#quick-start-docker---recommended)

Complete setup in 5 minutes for localhost MySQL:

```
# 1. Ensure user has Docker permissions
sudo usermod -aG docker $USER
newgrp docker  # Or log out/in

# 2. Create backup user in MariaDB/MySQL
sudo mysql &1

# 8. (Optional) Add retention - keep 30 days
# Add: 0 3 * * 0 find /path/to/mysql-db-backup/backups -name "*.sql.gz" -mtime +30 -delete
```

Done! Your backups will run daily at 2 AM. ✅

Installation
------------

[](#installation)

### Via Composer (Recommended)

[](#via-composer-recommended)

```
composer require indiehd/mysql-db-backup
```

### Manual Installation

[](#manual-installation)

```
git clone https://github.com/indiehd/mysql-db-backup.git
cd mysql-db-backup
composer install
```

Configuration
-------------

[](#configuration)

### Option 1: Configuration File (Recommended)

[](#option-1-configuration-file-recommended)

Copy the example configuration file and customize it:

```
cp db-backup.ini.example db-backup.ini
```

Edit `db-backup.ini`:

```
[connection]
hostname = localhost
username = your_mysql_user
password = your_mysql_password

[backup]
dumpdir = /path/to/backups
```

**Note:** The `password` field is optional if you're using socket-based authentication (e.g., `auth_socket` plugin in MariaDB).

### Option 2: Environment Variables

[](#option-2-environment-variables)

You can also configure using environment variables:

```
export DB_HOST=127.0.0.1      # Use 127.0.0.1, not localhost (for Docker)
export DB_USERNAME=your_mysql_user
export DB_PASSWORD=your_mysql_password
export BACKUP_DIR=/path/to/backups
```

Usage
-----

[](#usage)

### Command Line

[](#command-line)

If installed via Composer:

```
./vendor/bin/mysql-db-backup
```

If installed globally or from project directory:

```
./bin/mysql-db-backup
```

### Cron Job Setup

[](#cron-job-setup)

To run automated backups daily at 2 AM:

```
crontab -e
```

Add this line:

```
0 2 * * * cd /path/to/project && ./vendor/bin/mysql-db-backup >> /var/log/mysql-backup.log 2>&1
```

Or if using environment variables:

```
0 2 * * * DB_HOST=localhost DB_USERNAME=backup_user DB_PASSWORD=secret BACKUP_DIR=/backups /path/to/vendor/bin/mysql-db-backup >> /var/log/mysql-backup.log 2>&1
```

### Docker Usage

[](#docker-usage)

**For complete Docker deployment guide, see [DOCKER.md](DOCKER.md)**

#### Quick Start with Docker

[](#quick-start-with-docker)

```
# 1. Clone and build
git clone https://github.com/indiehd/mysql-db-backup.git
cd mysql-db-backup
git checkout composer
docker build -t mysql-db-backup -f docker/Dockerfile .

# 2. Create environment file (configure based on your scenario - see Database User Setup above)
cp .env.example .env
nano .env  # Edit with your credentials and network mode
chmod 600 .env

# 3. Test one-time backup
./run-backup.sh

# 4. Set up scheduled backups with cron
crontab -e
# Add: 0 2 * * * /path/to/mysql-db-backup/run-backup.sh >> /var/log/mysql-backup.log 2>&1
```

**The `run-backup.sh` script automatically handles different network modes based on your `.env` configuration.**

#### Manual Docker Run (if not using run-backup.sh)

[](#manual-docker-run-if-not-using-run-backupsh)

**Scenario A - Host Network:**

```
docker run --rm --network host --env-file .env \
  -v $(pwd)/backups:/backups mysql-db-backup
```

**Scenario B - Bridge Network:**

```
docker run --rm --env-file .env \
  -v $(pwd)/backups:/backups mysql-db-backup
```

**Scenario C - Custom Network:**

```
docker run --rm --network your_network --env-file .env \
  -v $(pwd)/backups:/backups mysql-db-backup
```

#### Using docker-compose

[](#using-docker-compose)

```
# Edit .env file first, then:
docker-compose up
```

How It Works
------------

[](#how-it-works)

1. **Connect** to MySQL/MariaDB server
2. **List** all databases (excluding system databases: `mysql`, `information_schema`, `performance_schema`, `sys`)
3. **Dump** each database using `mysqldump` with optimized flags
4. **Compare** the new backup hash with the previous backup
5. **Skip** if identical (no changes detected)
6. **Compress** with gzip if new data is present
7. **Store** in organized directory structure: `//.sql.gz`

Backup Optimization
-------------------

[](#backup-optimization)

The tool uses SHA1 hash comparison to avoid storing duplicate backups when database content hasn't changed. This saves significant storage space for databases that don't change frequently.

The dump files are created **without comments** (via `--skip-comments`) to ensure hash comparison works correctly, as comments include timestamps that would always differ.

Directory Structure
-------------------

[](#directory-structure)

```
/path/to/backups/
├── database1/
│   ├── 202602251400.sql.gz
│   ├── 202602261400.sql.gz
│   └── 202602271400.sql.gz
├── database2/
│   ├── 202602251400.sql.gz
│   └── 202602271400.sql.gz  # 26th skipped - no changes
└── database3/
    └── 202602251400.sql.gz

```

Backup Retention
----------------

[](#backup-retention)

**Important:** This tool does NOT automatically delete old backups. Backups will accumulate over time.

### Recommended: Add a Cleanup Cron Job

[](#recommended-add-a-cleanup-cron-job)

To prevent unlimited backup growth, add a retention policy:

```
# Keep backups for 30 days (weekly cleanup)
0 3 * * 0 find /path/to/backups -name "*.sql.gz" -mtime +30 -delete
```

**Common retention periods:**

- Development: 7-14 days
- Production: 30-90 days
- Compliance: May require longer (consult your requirements)

**Future Enhancement:** Built-in retention policies are planned for a future release.

Troubleshooting
---------------

[](#troubleshooting)

### Permission Issues

[](#permission-issues)

Ensure the backup directory is writable:

```
chmod 755 /path/to/backups
```

### MySQL Connection Issues

[](#mysql-connection-issues)

Test your connection:

```
mysql -h localhost -u your_user -p
```

### Missing Dependencies

[](#missing-dependencies)

Verify required executables are available:

```
which mysqldump gzip gunzip sha1sum
```

License
-------

[](#license)

GNU General Public License v3.0 or later (GPL-3.0-or-later)

Author
------

[](#author)

Ben Johnson ()

Copyright (c) 2012-2026, Ben Johnson

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance88

Actively maintained with recent releases

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

73d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/545562065314419514e3291df42c32ae0eee8063dab76ceee360a7f897d68747?d=identicon)[indieHD](/maintainers/indieHD)

---

Top Contributors

[![cbj4074](https://avatars.githubusercontent.com/u/1236883?v=4)](https://github.com/cbj4074 "cbj4074 (8 commits)")

---

Tags

automationdatabasebackupmysqlmariadbmysqldumpcron

### Embed Badge

![Health badge](/badges/indiehd-mysql-db-backup/health.svg)

```
[![Health](https://phpackages.com/badges/indiehd-mysql-db-backup/health.svg)](https://phpackages.com/packages/indiehd-mysql-db-backup)
```

###  Alternatives

[ifsnop/mysqldump-php

PHP version of mysqldump cli that comes with MySQL

1.3k5.5M69](/packages/ifsnop-mysqldump-php)[clouddueling/mysqldump-php

PHP version of mysqldump cli that comes with MySQL

1.3k22.9k](/packages/clouddueling-mysqldump-php)[rah/danpu

Zero-dependency MySQL dump library for easily exporting and importing databases

64401.8k10](/packages/rah-danpu)[druidfi/mysqldump-php

PHP version of mysqldump cli that comes with MySQL

35489.8k6](/packages/druidfi-mysqldump-php)[cytopia/mysqldump-secure

Secure mysqldump script with encryption, compression, logging, blacklisting and Nagios monitoring integration

1474.7k1](/packages/cytopia-mysqldump-secure)[phelium/mysql-backup

Backup easily your MySQL database !

278.2k2](/packages/phelium-mysql-backup)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
