File Manager V1.5
FILE_CONTENT: delete_listing.php
<?php
// CORS заголовки - должны быть в самом начале файла
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS");
header("Access-Control-Allow-Headers: Authorization, Content-Type, Accept, X-Requested-With, User-Agent, Origin");
header("Access-Control-Max-Age: 86400");
header("Access-Control-Allow-Credentials: true");
header("Content-Type: application/json; charset=UTF-8");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
// Обработка preflight OPTIONS запроса
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
header("Content-Length: 0");
exit(0);
}
$autoloadPath = __DIR__ . '/vendor/autoload.php';
$dbPath = __DIR__ . '/db.php';
if (!file_exists($autoloadPath)) {
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Файл vendor/autoload.php не найден', 'timestamp' => time()]);
exit;
}
if (!file_exists($dbPath)) {
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Файл db.php не найден', 'timestamp' => time()]);
exit;
}
require $autoloadPath;
require_once $dbPath;
function sendResponse($success, $message = '', $data = null, $code = 200) {
http_response_code($code);
echo json_encode([
'success' => $success,
'message' => $message,
'data' => $data,
'timestamp' => time()
]);
exit;
}
try {
$headers = getallheaders();
if (!isset($headers['Authorization'])) {
sendResponse(false, 'Требуется авторизация', null, 401);
}
$token = str_replace('Bearer ', '', $headers['Authorization']);
$decoded = verifyToken($token);
if ($decoded === false) {
sendResponse(false, 'Неверный или просроченный токен', null, 401);
}
$userId = $decoded['user_id'] ?? null;
if ($userId === null) {
sendResponse(false, 'Токен не содержит user_id', null, 401);
}
$input = json_decode(file_get_contents('php://input'), true);
if (!isset($input['listing_id'])) {
sendResponse(false, 'Отсутствует listing_id', null, 400);
}
$listingId = (int)$input['listing_id'];
$pdo = getPDO();
if (!$pdo) {
sendResponse(false, 'Ошибка подключения к БД. Проверьте db.php', null, 500);
}
$stmt = $pdo->query("SHOW TABLES LIKE 'bookings'");
if (!$stmt->fetch()) {
error_log("Table 'bookings' does not exist");
} else {
$stmt = $pdo->prepare("DELETE FROM bookings WHERE car_id = ?");
$stmt->execute([$listingId]);
}
$stmt = $pdo->query("SHOW TABLES LIKE 'car_listings'");
if (!$stmt->fetch()) {
sendResponse(false, 'Таблица car_listings не существует', null, 500);
}
$stmt = $pdo->prepare("SELECT user_id FROM car_listings WHERE id = ?");
$stmt->execute([$listingId]);
$listing = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$listing || $listing['user_id'] != $userId) {
sendResponse(false, 'Объявление не найдено или доступ запрещен', null, 403);
}
error_log("Attempting to delete listing ID: $listingId, user_id: $userId");
$stmt = $pdo->prepare("DELETE FROM car_listings WHERE id = ?");
$stmt->execute([$listingId]);
sendResponse(true, 'Объявление удалено', ['id' => $listingId]);
} catch (PDOException $e) {
error_log("PDOException: " . $e->getMessage());
sendResponse(false, 'Ошибка базы данных: ' . $e->getMessage(), null, 500);
} catch (Exception $e) {
error_log("Exception: " . $e->getMessage());
sendResponse(false, 'Ошибка сервера: ' . $e->getMessage(), null, 500);
}
?>[ KEMBALI ]