Last active
August 10, 2022 23:45
-
-
Save thotbox/34405661e2b2e6590504 to your computer and use it in GitHub Desktop.
PHP: Database FTP Backup
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
| <? | |
| $dbhost = 'localhost'; | |
| $dbuser = 'db_user'; | |
| $dbpass = 'db_pass'; | |
| $dbname = 'db_name'; | |
| $ftphost = 'ftp_host'; | |
| $ftpuser = 'ftp_user'; | |
| $ftppass = 'ftp_pass'; | |
| date_default_timezone_set('US/Eastern'); | |
| $dbfile = 'dumps/backup-' . date('Y-m-d-g-i') . '.sql'; | |
| $dbzip = 'dumps/backup-' . date('Y-m-d-g-i') . '.zip'; | |
| $ftpfile = 'backup-' . date('Y-m-d-g-i') . '.zip'; | |
| if ( file_exists($dbfile) ) { | |
| die('<p>File Exists.</p>'); | |
| } else { | |
| $link = mysql_connect($dbhost,$dbuser,$dbpass); | |
| if (!$link) { | |
| die('<p>Could not connect to database: ' . mysql_error() . '</p>'); | |
| } else { | |
| echo '<p>Database connection OK.</p>'; mysql_close($link); | |
| system("mysqldump -h $dbhost -u $dbuser -p$dbpass $dbname > $dbfile"); | |
| echo '<p>Database has been backed up locally.</p>'; | |
| $zip = new ZipArchive; | |
| $res = $zip->open($dbzip, ZipArchive::CREATE); | |
| $zip->addFile($dbfile); | |
| $zip->close(); | |
| $connection = ftp_connect($ftphost); | |
| $login = ftp_login($connection, $ftpuser, $ftppass); | |
| if (!$connection || !$login) { | |
| die('FTP connection failed.'); | |
| } | |
| $upload = ftp_put($connection, $ftpfile, $dbzip, FTP_ASCII); | |
| if (!$upload) { | |
| die('FTP upload failed'); | |
| } else { | |
| echo '<p>Database has been backed up to FTP.</p>'; | |
| $delete = unlink($dbfile); | |
| $deletezip = unlink($dbzip); | |
| if ($delete && $deletezip) { | |
| echo '<p>Local files deleted.</p>'; | |
| } | |
| } | |
| ftp_close($connection); | |
| } | |
| } | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment