Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

Site and MySQL backups via cron

  • Thread Author
Here is a straightforward approach for creating a backup, compressing it, and uploading it to an FTP server.

PHP:
<?php
$datestamp = date("Y-m-d_H-i-s");
$backup_dir = "/home/YOURACCOUNT/";
$filename = "Full_Account_Backup-$datestamp.tar.gz";
$full_path = $backup_dir . $filename;

$ftp_server = getenv('FTP_SERVER') ?: "123.123.123.123";
$ftp_port = getenv('FTP_PORT') ?: "21";
$ftp_username = getenv('FTP_USERNAME') ?: "anonymous";
$ftp_password = getenv('FTP_PASSWORD') ?: "";

// Create the backup
$command = "tar cvf $backup_dir/Full_Account_Backup-$datestamp.tar ~/* && gzip -9 $backup_dir/Full_Account_Backup-$datestamp.tar";
$result = shell_exec($command);
if ($result === null) {
    die("Backup creation failed.");
}

// Connect to FTP
$ftp_conn = ftp_connect($ftp_server, (int)$ftp_port);
if (!$ftp_conn || !ftp_login($ftp_conn, $ftp_username, $ftp_password)) {
    die("Failed to connect or login to FTP server.");
}

// Upload the file
ftp_pasv($ftp_conn, false);
if (!ftp_put($ftp_conn, $filename, $full_path, FTP_BINARY)) {
    echo "FTP upload failed.";
} else {
    echo "Uploaded $filename successfully.";
}

// Clean up
ftp_close($ftp_conn);
if (file_exists($full_path)) {
    unlink($full_path);
}
?>

MySQL backup via cron - Emailed to You

PHP:
<?php
// Load environment variables
$dbuser = getenv('DB_USER') ?: 'your_user';
$dbpwd = getenv('DB_PASSWORD') ?: 'your_password';
$dbname = getenv('DB_NAME') ?: 'your_database';
$backup_dir = "/path/to/backup/";

// Dynamic filename
$datestamp = date("Y-m-d");
$filename = $backup_dir . "backup-$datestamp.sql.gz";

// Backup command
$command = "mysqldump -u $dbuser --password=$dbpwd $dbname | gzip > $filename";
exec($command, $output, $return_var);

if ($return_var !== 0 || !file_exists($filename)) {
    die("Backup creation failed.");
}

// Email setup
$to = "you@remotesite.com";
$from = "you@yourhost.com";
$subject = "MySQL backup file";
$message = "Compressed database backup file attached.";

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);
try {
    $mail->setFrom($from, 'Backup System');
    $mail->addAddress($to);
    $mail->Subject = $subject;
    $mail->Body = $message;
    $mail->addAttachment($filename);
    
    $mail->send();
    echo "Backup emailed successfully.";
    unlink($filename);
} catch (Exception $e) {
    echo "Error sending email: " . $mail->ErrorInfo;
}
?>
 
Back
Top