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
if (isset($_FILES['image']) ) {
$title = trim($_POST['title']);
// File metadata
$file = $_FILES['image'];
$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileError = $file['error'];
$fileSize = $file['size'];
// Define allowed extensions and MIME types for safety
$allowedExtensions = ['jpg', 'jpeg', 'png', 'webp'];
$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
// Basic Validation
if ($fileError !== 0) {
die("Error uploading file.");
}
if (!in_array($fileExt, $allowedExtensions)) {
die("Invalid file type. Only JPG, JPEG, PNG, and WEBP are allowed.");
}
if ($fileSize > 5 * 1024 * 1024) { // 5MB Limit
die("File is too large. Maximum size is 5MB.");
}
// Generate a unique file name to prevent overriding existing files
$newFileName = uniqid('IMG_', true) . '.' . $fileExt;
$uploadFolder = 'pdf/';
$targetFilePath = $uploadFolder . $newFileName;
// 3. Move the file to the target directory and update the database
if (move_uploaded_file($fileTmpName, $targetFilePath)) {
$exam->data = array(
':id' => $_SESSION['user_id'],
':filename' => $fileName
);
$exam->query = "
INSERT INTO tableimages
(id,filename)
VALUES (:id,:filename)
";
$exam->execute_query();
$output = array(
'success' => 'add'
);
echo json_encode($output);
}
else
{
$output = array(
'er' => 'no add'
);
echo json_encode($output);
}
}
?> |
Partager