Files
sccs_laravel/app/Http/Controllers/BackupController.php
2025-11-04 16:23:40 +05:00

117 lines
3.9 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\Backup;
use Illuminate\Support\Facades\DB;
class BackupController extends Controller
{
public function index()
{
// $files = Storage::disk('public')->allFiles('uploads/sql');
$pageConfigs = [
'pageHeader' => true,
'showMenu' => true
];
$breadcrumbs = [['link' => '/admin/backup', 'name' => 'Home'], ['name' => 'Backup']];
$backups = Backup::all();
return view('content.backups', [
'pageConfigs' => $pageConfigs,
'breadcrumbs' => $breadcrumbs,
'backups' => $backups,
]);
}
public function createBackup(){
try {
$results=DB::transaction(function (){
$DB_HOST = 'localhost';
$DB_DATABASE = config('database.connections.mysql.database');
$DB_USERNAME = config('database.connections.mysql.username');
$DB_PASSWORD = config('database.connections.mysql.password');
$connection = mysqli_connect($DB_HOST, $DB_USERNAME, $DB_PASSWORD, $DB_DATABASE);
$tables = array();
$result = mysqli_query($connection, "SHOW TABLES");
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
$return = '';
foreach ($tables as $table) {
$result = mysqli_query($connection, "SELECT * FROM " . $table);
$num_fields = mysqli_num_fields($result);
$return .= 'DROP TABLE IF EXISTS ' . $table . ';';
$row2 = mysqli_fetch_row(mysqli_query($connection, "SHOW CREATE TABLE " . $table));
$return .= "\n\n" . $row2[1] . ";\n\n";
for ($i = 0; $i < $num_fields; $i++) {
while ($row = mysqli_fetch_row($result)) {
$return .= "INSERT INTO " . $table . " VALUES(";
for ($j = 0; $j < $num_fields; $j++) {
$row[$j] = addslashes($row[$j]);
if (isset($row[$j])) {
$return .= ($row[$j] == NULL || $row[$j] == '') ? 'NULL' : '"' . $row[$j] . '"';
} else {
$return .= 'NULL';
}
if ($j < $num_fields - 1) {
$return .= ',';
}
}
$return .= ");\n";
}
}
$return .= "\n\n\n";
}
if (!file_exists('backups')) {
mkdir('backups', 0777, true);
}
//save file
$name = 'database_backup_'. date('d_m_Y').'_'.time().'.sql';
$path = 'backups/' . $name;
$handle = fopen($path, "w+");
fwrite($handle, $return);
fclose($handle);
//save backup detail to db
Backup::create(['path' => $path]);
return true;
});
return redirect()->back()-> with([
'success' => "Database backup generated successfully"
]);
} catch (\Exception $e) {
return redirect()->back()-> with([
'error' => $e->getMessage()
]);
}
}
public function downloadBackup(Backup $backup)
{
return response()->download($backup->path);
}
public function deleteBackup(Backup $backup)
{
if (file_exists($backup->path)){
unlink($backup->path);
}
$backup->delete();
return redirect()->back()-> with([
'success' => "Database backup deleted successfully"
]);
}
}