Page 1 of 1

MYSQL backup script

Posted: Thu Dec 15, 2005 11:04 pm
by thockman
This is a modified php script to backup a phpwebsite db and html files then ftp them. I used some of the code from another script found on the net and I will
give the much deserved credit once I find where it was. :)

Code: Select all

<?php
/*
    File Name:    backupearp.php
    Author:        ?
    Modified by: Troy Hockman
    Description:     This is the php script to back up both the mysql database and files for earp.
            I have created a seperate file for each database and run it from the server the files
            are located.  Then cron it.  I know having passwords in the file is not good at all but
            it works for now.
    Dependencies:    Need to run from Linux box.  FTP server for uploads.
*/

/*
    Define variables for database and files.
    Leave $filepath blank for database only backup.
*/

$dbhost = "host";
$dbname = "dbname";
$user = "user";
$pass = "pass";
$filepath = "/www/html/*";
$tables = "";

// Start mysqldump for database
$tarfilename = $dbname."_backup"."_".date("n-j-y_H-i-s").".tar.gz";
$sqlfilename = $dbname."_backup"."_".date("n-j-y_H-i-s").".sql";
system("mysqldump --host=$dbhost --user=$user --password=$pass $dbname --quick --add-drop-table -c -l > $sqlfilename");

// Tar files
system("tar -cf $tarfilename $filepath $sqlfilename");

// Remove sqlfile now that it is in the tar
system("rm -f $sqlfilename");

// define some variables for ftp
$ftp_server = "xxx.xxx.xxx.xxx";
$ftp_user_name = "ftpuser";
$ftp_user_pass = "ftppass";
$destination_file = "backups/".$gzfilename;
$source_file = $gzfilename;

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// check connection
if ((!$conn_id) || (!$login_result)) {
    echo "FTP connection has failed!\n";
    echo "Attempted to connect to $ftp_server for user $ftp_user_name";
    exit();
} else {
    echo "Connected to $ftp_server, for user $ftp_user_name";
}

// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);

// check upload status
if (!$upload) {
    echo "FTP upload has failed!";
} else {
    echo "Uploaded $source_file to $ftp_server as $destination_file";
    system("rm -f $gzfilename $sqlfilename", $result);
}

// close the FTP stream
ftp_close($conn_id);
?>