getConnection(); $stmt = $pdo->prepare("SELECT source_xlsx_name, source_xlsx_path FROM work_sheets WHERE id = ?"); $stmt->execute([$id]); $row = $stmt->fetch(PDO::FETCH_ASSOC); if (!$row || empty($row['source_xlsx_path'])) { http_response_code(404); exit('Nessun file allegato a questo foglio'); } // Risoluzione sicura: il file deve stare dentro uploads/worksheets $abs = __DIR__ . '/' . $row['source_xlsx_path']; $real = realpath($abs); $baseDir = realpath(__DIR__ . '/uploads/worksheets'); if ($real === false || $baseDir === false || strpos($real, $baseDir) !== 0 || !is_file($real)) { http_response_code(404); exit('File non trovato'); } $downloadName = $row['source_xlsx_name'] !== '' ? $row['source_xlsx_name'] : basename($real); $asciiName = preg_replace('/[^A-Za-z0-9._-]/', '_', $downloadName); header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header("Content-Disposition: attachment; filename=\"{$asciiName}\"; filename*=UTF-8''" . rawurlencode($downloadName)); header('Content-Length: ' . filesize($real)); header('X-Content-Type-Options: nosniff'); header('Cache-Control: private, max-age=0, must-revalidate'); readfile($real); exit;