Files
sam-kd/shutterbox/put_shutterbox_image.php

103 lines
3.3 KiB
PHP
Raw Normal View History

<?php
// put_shutterbox_image.php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
if (!isset($_SESSION["level"]) || $_SESSION["level"] > 5) {
sleep(1);
header("HTTP/1.1 403 Forbidden");
exit;
}
$jsonFile = $_SERVER['DOCUMENT_ROOT'] . '/shutterbox/shutterbox.json';
// POST 필드
$box_width = trim($_POST['box_width'] ?? '');
$box_height = trim($_POST['box_height'] ?? '');
$exit_direction = trim($_POST['exit_direction'] ?? '');
$rail_width = trim($_POST['rail_width'] ?? '');
$front_bottom_width= trim($_POST['front_bottom_width']?? '');
$search_keyword = trim($_POST['search_keyword'] ?? '');
$index = isset($_POST['index']) ? intval($_POST['index']) : null;
// JSON 읽기
$shutterboxData = [];
if (file_exists($jsonFile)) {
$json = file_get_contents($jsonFile);
$shutterboxData = json_decode($json, true) ?: [];
}
// 이미지 업로드
$imagePath = '';
$uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/shutterbox/images/';
if (!file_exists($uploadDir)) mkdir($uploadDir, 0777, true);
if (isset($_FILES['upfile']) && $_FILES['upfile']['error'] === UPLOAD_ERR_OK) {
$orig = $_FILES['upfile']['name'];
$tmp = $_FILES['upfile']['tmp_name'];
$info = pathinfo($orig);
$name = preg_replace('/[^A-Za-z0-9_\-]/', '_', $info['filename']);
$new = date("Y_m_d_H_i_s") . "_{$name}" . (!empty($info['extension']) ? ".{$info['extension']}" : '');
$dest = $uploadDir . $new;
if (!move_uploaded_file($tmp, $dest)) {
echo json_encode(['error' => '파일 업로드 실패']);
exit;
}
$imagePath = '/shutterbox/images/' . $new;
} else {
echo json_encode(['error' => '업로드된 이미지가 없습니다']);
exit;
}
// 새 항목 배열
$newItem = [
'box_width' => $box_width,
'box_height' => $box_height,
'exit_direction' => $exit_direction,
'rail_width' => $rail_width,
'front_bottom_width'=> $front_bottom_width,
'search_keyword' => $search_keyword,
'image' => $imagePath
];
// 같은 조건의 데이터가 있는지 확인하고 덮어쓰기 또는 신규 추가
$foundIndex = null;
// 기존 데이터에서 같은 조건의 항목 찾기
foreach ($shutterboxData as $idx => $item) {
if ($item['box_width'] === $box_width &&
$item['box_height'] === $box_height &&
$item['exit_direction'] === $exit_direction &&
$item['rail_width'] === $rail_width &&
$item['front_bottom_width'] === $front_bottom_width &&
$item['search_keyword'] === $search_keyword) {
$foundIndex = $idx;
break;
}
}
// 덮어쓰기 or 신규 추가
if ($foundIndex !== null) {
// 같은 조건의 데이터가 있으면 덮어쓰기
$shutterboxData[$foundIndex] = $newItem;
$action = 'updated';
} else {
// 같은 조건의 데이터가 없으면 새로 추가
$shutterboxData[] = $newItem;
$action = 'added';
}
// JSON 저장
if (false === file_put_contents(
$jsonFile,
json_encode($shutterboxData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
)) {
echo json_encode(['error' => 'JSON 저장 실패']);
exit;
}
// 성공 응답
echo json_encode([
'success' => true,
'imagePath' => $imagePath,
'action' => $action,
'message' => $action === 'updated' ? '기존 데이터가 업데이트되었습니다.' : '새 데이터가 추가되었습니다.'
]);