Files
image-pichost/admin/ajax_delete_image.php
2025-11-30 13:07:29 +00:00

37 lines
1.2 KiB
PHP

<?php
require_once '../config.php';
if (!isset($_SESSION['user_id']) || $_SESSION['username'] !== 'admin') {
echo json_encode(['success' => false, 'error' => '无权限']);
exit;
}
$input = json_decode(file_get_contents('php://input'), true);
if ($input && isset($input['image_id'])) {
try {
// 先获取文件名以便删除物理文件
$stmt = $pdo->prepare("SELECT filename FROM images WHERE id = ?");
$stmt->execute([$input['image_id']]);
$image = $stmt->fetch(PDO::FETCH_ASSOC);
if ($image) {
// 删除数据库记录(会级联删除关联的标签)
$stmt = $pdo->prepare("DELETE FROM images WHERE id = ?");
$stmt->execute([$input['image_id']]);
// 删除物理文件
$file_path = '../uploads/' . $image['filename'];
if (file_exists($file_path)) {
unlink($file_path);
}
}
echo json_encode(['success' => true]);
} catch(PDOException $e) {
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
} else {
echo json_encode(['success' => false, 'error' => '无效请求']);
}
?>