Files
PHP/delete_image.php
2026-11-27 15:42:12 +08:00

76 lines
2.4 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
require_once __DIR__ . '/includes/auth.php';
header('Content-Type: application/json; charset=utf-8');
$user = current_user($conn);
if (!$user) {
http_response_code(401);
echo json_encode(['ok' => false, 'msg' => '登录已失效,请重新登录']);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !csrf_ok()) {
http_response_code(400);
echo json_encode(['ok' => false, 'msg' => '请求校验失败']);
exit;
}
$raw = $_POST['ids'] ?? ($_POST['id'] ?? '');
$ids = array_values(array_unique(array_filter(
array_map('intval', explode(',', (string)$raw)),
fn($v) => $v > 0
)));
if (!$ids) {
echo json_encode(['ok' => false, 'msg' => '未选择图片']);
exit;
}
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$types = str_repeat('i', count($ids)) . 'i';
$args = array_merge($ids, [$user['user_id']]);
$stmt = $conn->prepare("SELECT image_id, image_path FROM images WHERE image_id IN ($placeholders) AND user_id = ?");
$stmt->bind_param($types, ...$args);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
$deleted = 0;
foreach ($rows as $row) {
$d = $conn->prepare("DELETE FROM images WHERE image_id = ? AND user_id = ?");
$d->bind_param("ii", $row['image_id'], $user['user_id']);
$d->execute();
$hit = $d->affected_rows;
$deleted += $hit;
$d->close();
if ($hit > 0) {
// 图片若在广场,级联删除(FK ON DELETE CASCADE);显式删一次让意图一目了然
$sq = $conn->prepare("DELETE FROM photos_square WHERE image_id = ?");
$sq->bind_param("i", $row['image_id']);
$sq->execute();
$sq->close();
$uploads_dir = realpath(__DIR__ . '/uploads');
$full = realpath(__DIR__ . '/' . $row['image_path']);
if ($full && $uploads_dir && strpos($full, $uploads_dir) === 0 && is_file($full)) {
@unlink($full);
}
}
}
$refunded = 0;
if ($deleted > 0) {
$refunded = $deleted;
$u = $conn->prepare("UPDATE photo_users SET points = points + ? WHERE user_id = ?");
$u->bind_param("ii", $refunded, $user['user_id']);
$u->execute();
$u->close();
}
echo json_encode([
'ok' => true,
'deleted' => $deleted,
'refunded' => $refunded,
'points' => $user['points'] + $refunded,
], JSON_UNESCAPED_UNICODE);