zibo-dashboard/public/userarea/delete_matrice_attachment.php

62 lines
1.6 KiB
PHP

<?php
include('include/headscript.php');
header('Content-Type: application/json; charset=utf-8');
$response = [
'success' => false,
'message' => ''
];
try {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
throw new Exception('Metodo non consentito');
}
if (!isset($_POST['id']) || !is_numeric($_POST['id'])) {
throw new Exception('ID allegato non valido');
}
$id = (int)$_POST['id'];
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
$stmt = $pdo->prepare("SELECT id, file_path FROM matrice_attachments WHERE id = :id LIMIT 1");
$stmt->execute([':id' => $id]);
$attachment = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$attachment) {
throw new Exception('Allegato non trovato');
}
$filePathRelative = ltrim((string)$attachment['file_path'], '/\\');
$filePathAbsolute = __DIR__ . '/' . $filePathRelative;
$pdo->beginTransaction();
$deleteStmt = $pdo->prepare("DELETE FROM matrice_attachments WHERE id = :id");
$deleteStmt->execute([':id' => $id]);
if ($deleteStmt->rowCount() <= 0) {
throw new Exception('Impossibile eliminare il record allegato');
}
if (!empty($filePathRelative) && file_exists($filePathAbsolute) && is_file($filePathAbsolute)) {
@unlink($filePathAbsolute);
}
$pdo->commit();
$response['success'] = true;
$response['message'] = 'Allegato eliminato correttamente';
} catch (Throwable $e) {
if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) {
$pdo->rollBack();
}
$response['message'] = $e->getMessage();
}
echo json_encode($response, JSON_UNESCAPED_UNICODE);
exit;