What are some best practices for uploading images of various formats in PHP and storing their names in a MySQL database?
When uploading images of various formats in PHP and storing their names in a MySQL database, it is important to handle file uploads securely and efficiently. One best practice is to validate the file type and size before storing it. Additionally, generating a unique filename to avoid conflicts and storing only the filename in the database can help maintain a clean and organized file system.
<?php
// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Check if a file was selected for upload
if (isset($_FILES["image"]) && $_FILES["image"]["error"] == 0) {
$target_dir = "uploads/";
$target_file = $target_dir . uniqid() . '_' . basename($_FILES["image"]["name"]);
// Validate file type
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
if ($imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType != "png" && $imageFileType != "gif") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
} else {
// Move the uploaded file to the target directory
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
// Store the filename in the database
$filename = basename($target_file);
// Perform MySQL query to store $filename in the database
echo "The file " . $filename . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
} else {
echo "No file selected for upload.";
}
}
?>