<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
$uploadDir = __DIR__ . "/images/";
// Create directory if it doesn't exist
if (!file_exists($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
if (!isset($_FILES['image'])) {
echo json_encode(['success' => false, 'error' => 'No file uploaded']);
exit;
}
$file = $_FILES['image'];
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if (!in_array($file['type'], $allowedTypes)) {
echo json_encode(['success' => false, 'error' => 'Invalid file type. Only JPG, PNG, GIF, and WEBP allowed.']);
exit;
}
// Generate unique filename
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = uniqid('img_') . '.' . $extension;
$targetPath = $uploadDir . $filename;
if (move_uploaded_file($file['tmp_name'], $targetPath)) {
$url = 'images/' . $filename;
echo json_encode(['success' => true, 'url' => $url]);
} else {
echo json_encode(['success' => false, 'error' => 'Failed to save file']);
}
?>