-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsave_image.php
More file actions
67 lines (56 loc) · 2.24 KB
/
save_image.php
File metadata and controls
67 lines (56 loc) · 2.24 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
<?php
session_start();
if (!isset($_SESSION['username'])) {
header('Location: login.php');
exit;
}
require_once __DIR__ . '/includes/Database.php';
$type = $_POST['type'] ?? '';
$id = $_POST['id'] ?? '';
$description = $_POST['description'] ?? '';
if (!in_array($type, ['element', 'theme', 'biocultural']) || !is_numeric($id)) {
die('Invalid data.');
}
// File handling
if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
$allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$uploadDir = 'uploads/';
$fileTmpPath = $_FILES['image']['tmp_name'];
$fileName = basename($_FILES['image']['name']);
$ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
if (!in_array($ext, $allowed)) {
die('File type not allowed.');
}
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
$newFileName = uniqid('img_', true) . '.' . $ext;
$destPath = $uploadDir . $newFileName;
if (move_uploaded_file($fileTmpPath, $destPath)) {
$pdo = Database::connect();
$stmt = $pdo->prepare("INSERT INTO images (related_type, id_source, filename, caption, uploaded_at) VALUES (?, ?, ?, ?, NOW())");
$stmt->execute([$type, $id, $newFileName, $description]);
header("Location: geosite.php?fid=" . ($type === 'element' ? getFidForElement($pdo, $id) : findFidByType($pdo, $type, $id)));
exit();
} else {
die('The image has not been saved.');
}
} else {
die('An error occured when sending image.');
}
function getFidForElement($pdo, $id_element) {
$stmt = $pdo->prepare("SELECT fid FROM elements WHERE id_element = ?");
$stmt->execute([$id_element]);
return $stmt->fetchColumn() ?: 0;
}
function findFidByType($pdo, $type, $id) {
if ($type === 'theme') {
$stmt = $pdo->prepare("SELECT e.fid FROM elements e JOIN themes t ON t.id_element = e.id_element WHERE t.id_theme = ?");
} elseif ($type === 'biocultural') {
$stmt = $pdo->prepare("SELECT e.fid FROM elements e JOIN bioculturals b ON b.id_element = e.id_element WHERE b.id_biocul = ?");
} else {
return 0;
}
$stmt->execute([$id]);
return $stmt->fetchColumn() ?: 0;
}