Files
RecruIT/app/Http/Controllers/BackupController.php
2026-03-28 07:59:17 +01:00

61 lines
2.0 KiB
PHP

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use ZipArchive;
class BackupController extends Controller
{
public function download()
{
$databaseName = env('DB_DATABASE');
$userName = env('DB_USERNAME');
$password = env('DB_PASSWORD');
$host = env('DB_HOST', '127.0.0.1');
$backupFileName = 'backup_quizzcabm_' . date('Y-m-d_H-i-s') . '.zip';
$backupFilePath = storage_path('app/' . $backupFileName);
$sqlDumpFilePath = storage_path('app/dump.sql');
// Execute mysqldump
$command = "mysqldump --user={$userName} --password={$password} --host={$host} {$databaseName} > " . escapeshellarg($sqlDumpFilePath);
if (empty($password)) {
$command = "mysqldump --user={$userName} --host={$host} {$databaseName} > " . escapeshellarg($sqlDumpFilePath);
}
exec($command);
$zip = new ZipArchive;
if ($zip->open($backupFilePath, ZipArchive::CREATE) === TRUE) {
// Add DB dump
if (file_exists($sqlDumpFilePath)) {
$zip->addFile($sqlDumpFilePath, 'database.sql');
}
// Add documents specifically searching the local disk
$allFiles = Storage::disk('local')->allFiles();
foreach ($allFiles as $filePath) {
$fullPath = Storage::disk('local')->path($filePath);
// The zip structure will have a folder 'storage_files' containing the relative path
$zip->addFile($fullPath, 'storage_files/' . $filePath);
}
$zip->close();
}
if (file_exists($sqlDumpFilePath)) {
unlink($sqlDumpFilePath);
}
if (file_exists($backupFilePath)) {
return response()->download($backupFilePath)->deleteFileAfterSend(true);
}
return back()->with('error', 'Erreur lors de la création de la sauvegarde.');
}
}