Primeros pasos sistema backup

This commit is contained in:
imnavajas
2025-05-02 14:10:49 +02:00
parent 746955c3b1
commit d7a85ca04f
8 changed files with 172 additions and 63 deletions

View File

@ -0,0 +1,83 @@
<?php
namespace App\Controllers\Sistema;
use App\Controllers\BaseController;
use phpseclib3\Net\SFTP;
class Backups extends BaseController
{
public function index()
{
helper('filesystem');
// Muestra la vista con la lista de backups
$files = directory_map(WRITEPATH . 'backups/', 1);
return view('themes/vuexy/form/backups/backupList', ['files' => $files]);
}
public function create()
{
helper('filesystem');
$filename = 'backup_' . date('Ymd_His') . '.sql';
$path = WRITEPATH . 'backups/' . $filename;
$dbConfig = config('Database')->default;
$host = $dbConfig['hostname'];
$username = $dbConfig['username'];
$password = $dbConfig['password'];
$database = $dbConfig['database'];
$command = "mysqldump -h {$host} -u{$username} -p'{$password}' {$database} > {$path}";
system($command, $retval);
if ($retval !== 0) {
throw new \RuntimeException("Error al crear el backup.");
}
// Enviar a SFTP
$this->sendToSFTP($path, $filename);
return redirect()->to(route_to('backupsList'))->with('message', 'Backup creado y enviado.');
}
public function restore($file)
{
$path = WRITEPATH . 'backups/' . $file;
if (!file_exists($path)) {
throw new \CodeIgniter\Exceptions\PageNotFoundException("Backup no encontrado.");
}
$db = \Config\Database::connect();
$sql = file_get_contents($path);
$db->query('SET FOREIGN_KEY_CHECKS=0;');
$db->query($sql);
$db->query('SET FOREIGN_KEY_CHECKS=1;');
return redirect()->to('/backups')->with('message', 'Backup restaurado.');
}
private function sendToSFTP($localPath, $remoteFilename)
{
$sftpHost = 'sftp.hidrive.ionos.com';
$sftpUser = 'erp2019';
$sftpPass = 'Z2CjX7kd2h';
$remotePath = '/users/erp2019/backups_erp/' . $remoteFilename;
$sftp = new SFTP($sftpHost);
if (!$sftp->login($sftpUser, $sftpPass)) {
throw new \RuntimeException('Error de autenticación SFTP');
}
$fileContents = file_get_contents($localPath);
if (!$sftp->put($remotePath, $fileContents)) {
throw new \RuntimeException("No se pudo subir el backup al servidor SFTP.");
}
}
}