CasperSecurity
<?php
namespace App\Console\Commands;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\App;
use phpseclib\Net\SFTP;
use phpseclib\Net\SSH2;
class DatabaseBackup extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'db:backup';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Allows you to backup your local database.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$filename = "backup-" . Carbon::now()->format('Y-m-d') . ".sql";
$command = "".env('DUMP_PATH')." --no-tablespaces --user=" . env('DB_USERNAME') . " --password=" . env('DB_PASSWORD') . " --host=" . env('DB_HOST') . " " . env('DB_DATABASE') . " > " . storage_path() . "/app/backup/" . $filename;
$returnVar = NULL;
$output = NULL;
exec($command, $output, $returnVar);
$remote_host = env('REMOTE_HOST');
$remote_port = env('REMOTE_PORT');
$remote_url = env('REMOTE_SYNC_URL');
$remote_db = env('REMOTE_SYNC_DB_NAME');
$remote_db_user = env('REMOTE_SYNC_DB_USERNAME');
$remote_db_pass = env('REMOTE_SYNC_DB_PASSWORD');
$ssh_user = env('REMOTE_SYNC_SSH_USERNAME');
$ssh_pass = env('REMOTE_SYNC_SSH_PASSWORD');
if (App::environment('production')) {
$this->error("Please don't try and run this in production... will not end well.");
return;
}
if(!$remote_db || !$remote_db || !$ssh_user || !$ssh_pass){
$this->error('Add your environment variables!');
return;
}
$ssh = new SSH2($remote_url);
if (!$ssh->login($ssh_user, $ssh_pass)) {
$this->error('Login failed make sure your ssh username and password is set in your env file.');
return;
}else{
$this->info('Connceted Successfully.');
}
$sftp = new SFTP($remote_url);
if (!$sftp->login($ssh_user, $ssh_pass)) {
$this->error('Login failed make sure your SSH username and password is set in your env file.');
return;
}
// Temporarily remove memory limit
ini_set('memory_limit', '-1');
$this->info('Uploading the backup.');
$sftp->put('sync_backup.sql', storage_path().'/app/backup/'.$filename, SFTP::SOURCE_LOCAL_FILE);
$this->info('Importing...');
$ssh->exec("mysql -u ".$remote_db_user." --password=".$remote_db_pass." -D ".$remote_db." -h ".$remote_host." -P ".$remote_port." < sync_backup.sql");
$ssh->exec('rm sync_backup.sql');
$this->info('Complete! You are synced with the remote DB.');
}
}