-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgallery.php
More file actions
207 lines (176 loc) · 6.58 KB
/
gallery.php
File metadata and controls
207 lines (176 loc) · 6.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
<?php
require_once 'config.php';
// Check if user is logged in
if (!isLoggedIn()) {
sendResponse(false, 'Authentication required');
}
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
case 'GET':
getAllImages();
break;
case 'POST':
uploadImages();
break;
case 'DELETE':
parse_str(file_get_contents("php://input"), $_DELETE);
deleteImage($_DELETE['id'] ?? null);
break;
default:
sendResponse(false, 'Method not allowed');
}
function getAllImages() {
global $pdo;
try {
// Join with categories table to get category name
$stmt = $pdo->query("
SELECT g.*, c.name as category_name
FROM gallery g
LEFT JOIN categories c ON g.category_id = c.id
ORDER BY g.uploaded_at DESC
");
$images = $stmt->fetchAll();
sendResponse(true, 'Images retrieved successfully', $images);
} catch(PDOException $e) {
sendResponse(false, 'Database error: ' . $e->getMessage());
}
}
function uploadImages() {
global $pdo;
if (!isset($_FILES['images']) || empty($_FILES['images']['name'][0])) {
sendResponse(false, 'No images selected');
}
// Get category_id from POST data - FIXED: Check for array format
$categoryId = null;
// Handle both single value and array format for category_id
if (isset($_POST['category_id'])) {
if (is_array($_POST['category_id'])) {
$categoryId = !empty($_POST['category_id'][0]) ? (int)$_POST['category_id'][0] : null;
} else {
$categoryId = !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null;
}
}
// Debug logging - remove in production
error_log("Category ID received: " . var_export($categoryId, true));
error_log("POST data: " . var_export($_POST, true));
// Validate category exists if provided
if ($categoryId) {
try {
$stmt = $pdo->prepare("SELECT id FROM categories WHERE id = ?");
$stmt->execute([$categoryId]);
if (!$stmt->fetch()) {
sendResponse(false, 'Selected category does not exist');
return;
}
} catch(PDOException $e) {
sendResponse(false, 'Category validation error: ' . $e->getMessage());
return;
}
}
$uploadDir = 'uploads/gallery/';
// Create upload directory if it doesn't exist
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
$uploadedImages = [];
$errors = [];
// Handle both single file and multiple files
$files = $_FILES['images'];
$fileCount = is_array($files['name']) ? count($files['name']) : 1;
for ($i = 0; $i < $fileCount; $i++) {
// Handle both array and single file formats
if (is_array($files['name'])) {
$fileName = $files['name'][$i];
$fileTmpName = $files['tmp_name'][$i];
$fileSize = $files['size'][$i];
$fileError = $files['error'][$i];
$fileType = $files['type'][$i];
} else {
$fileName = $files['name'];
$fileTmpName = $files['tmp_name'];
$fileSize = $files['size'];
$fileError = $files['error'];
$fileType = $files['type'];
}
// Skip if no file
if ($fileError === UPLOAD_ERR_NO_FILE) {
continue;
}
// Check for upload errors
if ($fileError !== UPLOAD_ERR_OK) {
$errors[] = "Upload error for file: $fileName";
continue;
}
// Validate file type
$allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
if (!in_array($fileType, $allowedTypes)) {
$errors[] = "Invalid file type for: $fileName. Only JPEG, PNG, GIF, and WebP are allowed.";
continue;
}
// Validate file size (5MB max)
if ($fileSize > 5 * 1024 * 1024) {
$errors[] = "File too large: $fileName. Maximum size is 5MB.";
continue;
}
// Generate unique filename
$fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
$uniqueFileName = uniqid() . '_' . time() . '.' . $fileExtension;
$targetPath = $uploadDir . $uniqueFileName;
// Move uploaded file
if (move_uploaded_file($fileTmpName, $targetPath)) {
try {
// Save to database WITH category_id
$stmt = $pdo->prepare("INSERT INTO gallery (name, url, category_id, uploaded_at) VALUES (?, ?, ?, NOW())");
$stmt->execute([$fileName, $targetPath, $categoryId]);
$uploadedImages[] = [
'id' => $pdo->lastInsertId(),
'name' => $fileName,
'url' => $targetPath,
'category_id' => $categoryId,
'uploaded_at' => date('Y-m-d H:i:s')
];
} catch(PDOException $e) {
$errors[] = "Database error for $fileName: " . $e->getMessage();
// Remove the uploaded file if database insert fails
unlink($targetPath);
}
} else {
$errors[] = "Failed to move uploaded file: $fileName";
}
}
if (!empty($uploadedImages)) {
$message = count($uploadedImages) . ' image(s) uploaded successfully';
if (!empty($errors)) {
$message .= '. Some files had errors: ' . implode(', ', $errors);
}
sendResponse(true, $message, $uploadedImages);
} else {
sendResponse(false, 'No images were uploaded. Errors: ' . implode(', ', $errors));
}
}
function deleteImage($id) {
global $pdo;
if (!$id) {
sendResponse(false, 'Image ID is required');
}
try {
// Get image info before deleting
$stmt = $pdo->prepare("SELECT url FROM gallery WHERE id = ?");
$stmt->execute([$id]);
$image = $stmt->fetch();
if (!$image) {
sendResponse(false, 'Image not found');
}
// Delete from database
$stmt = $pdo->prepare("DELETE FROM gallery WHERE id = ?");
$stmt->execute([$id]);
// Delete physical file
if (file_exists($image['url'])) {
unlink($image['url']);
}
sendResponse(true, 'Image deleted successfully');
} catch(PDOException $e) {
sendResponse(false, 'Database error: ' . $e->getMessage());
}
}
?>