-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload.php
More file actions
77 lines (63 loc) · 2.63 KB
/
upload.php
File metadata and controls
77 lines (63 loc) · 2.63 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
<?php
require_once 'db.php';
require_once 'auth.php';
// Upload image
function uploadImage($file) {
// Check if user is logged in
if (!isLoggedIn()) {
return ['success' => false, 'error' => 'Must be logged in to upload'];
}
// Validate file
if (!isset($file) || $file['error'] !== UPLOAD_ERR_OK) {
return ['success' => false, 'error' => 'File upload error'];
}
// Check file size (max 10MB)
if ($file['size'] > 10 * 1024 * 1024) {
return ['success' => false, 'error' => 'File too large (max 10MB)'];
}
// Get file extension
$originalFilename = $file['name'];
$extension = strtolower(pathinfo($originalFilename, PATHINFO_EXTENSION));
// Validate extension
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
if (!in_array($extension, $allowedExtensions)) {
return ['success' => false, 'error' => 'Invalid file type'];
}
// Verify it's actually an image
$imageInfo = getimagesize($file['tmp_name']);
if ($imageInfo === false) {
return ['success' => false, 'error' => 'File is not a valid image'];
}
$db = getDB();
$userId = getCurrentUserId();
// Insert into database first to get the ID
$stmt = $db->prepare('INSERT INTO images (user_id, filename, original_filename, file_size) VALUES (:user_id, :filename, :original_filename, :file_size)');
$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
$stmt->bindValue(':filename', 'temp', SQLITE3_TEXT);
$stmt->bindValue(':original_filename', $originalFilename, SQLITE3_TEXT);
$stmt->bindValue(':file_size', $file['size'], SQLITE3_INTEGER);
if (!$stmt->execute()) {
return ['success' => false, 'error' => 'Database error'];
}
// Get the inserted ID
$imageId = $db->lastInsertRowID();
// Generate filename with base62 encoding
$filename = generateFilename($imageId, $extension);
$uploadPath = '/www/imguruk.com/web/uploads/' . $filename;
// Move uploaded file
if (!move_uploaded_file($file['tmp_name'], $uploadPath)) {
// Rollback: delete database entry
$db->exec("DELETE FROM images WHERE id = $imageId");
return ['success' => false, 'error' => 'Failed to save file'];
}
// Update database with actual filename
$updateStmt = $db->prepare('UPDATE images SET filename = :filename WHERE id = :id');
$updateStmt->bindValue(':filename', $filename, SQLITE3_TEXT);
$updateStmt->bindValue(':id', $imageId, SQLITE3_INTEGER);
$updateStmt->execute();
return [
'success' => true,
'filename' => $filename,
'url' => 'https://i.imguruk.com/' . $filename
];
}