Last active
February 25, 2022 08:46
-
-
Save sdon2/72d0e46484936d092ceb90ead7807388 to your computer and use it in GitHub Desktop.
Database Backup PHP Script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env php | |
<?php | |
require __DIR__ . "/vendor/autoload.php"; | |
use Spatie\DbDumper\Databases\MySql; | |
use Spatie\DbDumper\Compressors\GzipCompressor; | |
use Symfony\Component\Mailer\Transport; | |
use Symfony\Component\Mailer\Mailer as SymfonyMailer; | |
use Symfony\Component\Mime\Email; | |
$db_host = "127.0.0.1"; | |
$db_name = ""; | |
$db_username = ""; | |
$db_password = ""; | |
$dump_file_path = __DIR__ . '/backup.sql.gz'; | |
$email_username = ""; | |
$email_password = ""; | |
$email_host = "smtp.gmail.com"; | |
$email_port = 587; | |
$email_to = ""; | |
$email_subject = "Database backup: " . date('d-m-Y'); | |
$result = -1; | |
try { | |
// Create dump | |
MySql::create() | |
->setHost($db_host) | |
->setDbName($db_name) | |
->setUserName($db_username) | |
->setPassword($db_password) | |
->useCompressor(new GzipCompressor) | |
->dumpToFile($dump_file_path); | |
// Send Email | |
$transport = Transport::fromDsn(sprintf("smtp://%s:%s@%s:%s", urlencode($email_username), urlencode($email_password), $email_host, $email_port)); | |
$mailer = new SymfonyMailer($transport); | |
$email = (new Email()) | |
->from($email_username) | |
->to($email_to) | |
->subject($email_subject) | |
->text("PFA") | |
->attachFromPath($dump_file_path); | |
$mailer->send($email); | |
$result = 0; | |
} catch (\Exception $ex) { | |
echo "\n" . $ex->getMessage(); | |
$result = -1; | |
} finally { | |
if (file_exists($dump_file_path)) { | |
unlink($dump_file_path); | |
} | |
exit($result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment