Files
2026-03-05 10:25:39 +01:00

56 lines
1.5 KiB
PHP

<?php
// /admin/tools/logs_download.php
declare(strict_types=1);
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
// 1) Sécurité: admin requis
if (empty($_SESSION['role']) || !in_array('admin', (array)$_SESSION['role'], true)) {
http_response_code(403);
echo 'Forbidden';
exit;
}
// 2) CSRF GET
if (empty($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_GET['csrf'] ?? '')) {
http_response_code(400);
echo 'CSRF invalid';
exit;
}
// 3) Map fichiers autorisés
$siteRoot = realpath(__DIR__ . '/../../');
$logsDir = $siteRoot . '/logs';
$map = [
'php_errors' => $logsDir . '/php_errors.log',
'app' => $logsDir . '/app.log',
];
$key = $_GET['file'] ?? 'php_errors';
$path = $map[$key] ?? $map['php_errors'];
// 4) S'assurer que le dossier/fichier existe
if (!is_dir($logsDir)) { @mkdir($logsDir, 0755, true); }
if (!file_exists($path)) { @touch($path); } // crée un .log vide si absent
// 5) Lecture sûre
if (!is_file($path) || !is_readable($path)) {
http_response_code(404);
echo 'Log file not found or unreadable';
exit;
}
// 6) Purge des buffers et envoi
while (ob_get_level()) { ob_end_clean(); }
$size = filesize($path) ?: 0;
$filename = $key.'_'.date('Ymd_His').'.log';
header('Content-Type: text/plain; charset=utf-8');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Length: '.$size);
header('Cache-Control: no-store');
$fp = fopen($path, 'rb');
if ($fp) { fpassthru($fp); fclose($fp); } else { readfile($path); }
exit;