Skip to content

Instantly share code, notes, and snippets.

@dlebech
Created March 12, 2024 14:58
Show Gist options
  • Save dlebech/991c892b0050bf57a643b19c97f0d2f4 to your computer and use it in GitHub Desktop.
Save dlebech/991c892b0050bf57a643b19c97f0d2f4 to your computer and use it in GitHub Desktop.
mysqldump-php to Google Cloud Storage with gzip streaming
<?php
# Public Domain CC0 license. https://creativecommons.org/publicdomain/zero/1.0/
# Install requirements:
# composer require ifsnop/mysqldump-php
# composer require google/cloud-storage
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/config.php';
use Ifsnop\Mysqldump as IMysqldump;
use Google\Cloud\Storage\StorageClient;
$database = DB_NAME;
$user = DB_USER;
$pass = DB_PASS;
$host = DB_HOST;
$bucket = GCS_BACKUP_BUCKET;
// GCS_KEY_FILE contains a string of the JSON contents of a Google Cloud Service Account
// Alternatively store the JSON file locally and read it with get file contents, etc.
$storage = new StorageClient([
'keyFile' => json_decode(GCS_KEY_FILE, true),
]);
// Register storage client for gs:// paths
$storage->registerStreamWrapper();
$objectName = "gs://$bucket/" . date('Y-m-d_His') . ".sql.gz";
try {
$dump = new IMysqldump\Mysqldump("mysql:host=$host;dbname=$database", $user, $pass, [
'compress' => IMysqldump\Mysqldump::GZIPSTREAM,
]);
$dump->start($objectName);
} catch (\Exception $e) {
echo 'mysqldump-php error: ' . $e->getMessage();
}
echo 'Backup complete' . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment