mirror of
https://github.com/myronblair/tomsjavajive
synced 2026-06-30 17:50:32 -05:00
49 lines
1.4 KiB
PHP
49 lines
1.4 KiB
PHP
<?php
|
|
/**
|
|
* Tom's Java Jive - Admin Image Upload Handler
|
|
*/
|
|
require_once __DIR__ . '/../includes/auth.php';
|
|
require_once __DIR__ . '/../includes/db.php';
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
if (!AdminAuth::getUser()) {
|
|
http_response_code(401);
|
|
echo json_encode(['error' => 'Unauthorized']);
|
|
exit;
|
|
}
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_FILES['image'])) {
|
|
echo json_encode(['error' => 'No file received']);
|
|
exit;
|
|
}
|
|
|
|
$file = $_FILES['image'];
|
|
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
|
|
$maxSize = 5 * 1024 * 1024; // 5MB
|
|
|
|
if (!in_array($file['type'], $allowedTypes)) {
|
|
echo json_encode(['error' => 'Invalid file type. Use JPG, PNG, WebP, or GIF.']);
|
|
exit;
|
|
}
|
|
|
|
if ($file['size'] > $maxSize) {
|
|
echo json_encode(['error' => 'File too large. Maximum 5MB.']);
|
|
exit;
|
|
}
|
|
|
|
$uploadDir = __DIR__ . '/../uploads/products/';
|
|
if (!is_dir($uploadDir)) {
|
|
mkdir($uploadDir, 0755, true);
|
|
}
|
|
|
|
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
|
|
$filename = 'product_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
|
|
$filepath = $uploadDir . $filename;
|
|
|
|
if (move_uploaded_file($file['tmp_name'], $filepath)) {
|
|
echo json_encode(['success' => true, 'url' => '/uploads/products/' . $filename]);
|
|
} else {
|
|
echo json_encode(['error' => 'Failed to save file. Check directory permissions.']);
|
|
}
|