<?php
// Validate uploaded image
if ($gambar['error'] !== UPLOAD_ERR_OK) {
echo "Error uploading image. Please try again.";
} else {
$file_name = $gambar['name'];
$file_size = $gambar['size'];
$file_tmp = $gambar['tmp_name'];
$file_type = $gambar['type'];
$allowed_extensions = array("image/jpeg", "image/jpg", "image/png", "image/gif");
$max_file_size = 5 * 1024 * 1024; // 5MB
if (!in_array($file_type, $allowed_extensions)) {
echo "Invalid file type. Allowed types are JPG, JPEG, PNG, and GIF.";
} elseif ($file_size > $max_file_size) {
echo "File size is too large. Maximum file size is 5MB.";
} else {
// Generate a unique random file name
$unique_filename = uniqid() . '_' . $file_name;
// Move the uploaded image to a designated folder with the unique file name
$upload_path = "img/";
$destination = $upload_path . $unique_filename;
if (move_uploaded_file($file_tmp, $destination)) {
// Insert the data into the database
$query = "INSERT INTO books (judul, gambar, kategori, isi) VALUES ('$judul', '$destination', '$kategori', '$isi')";
mysqli_query($conn, $query);
if (mysqli_affected_rows($conn) > 0) {
header("Location: index.php");
} else {
echo "Error inserting data into the database.";
}
} else {
echo "Error moving the uploaded image.";
}
}
}