In today’s digital world, image upload is essential for web development. Whether you’re building a social media platform, an e-commerce site, or a personal blog, allowing users to upload multiple images can enhance the user experience. This tutorial will teach you how to build a multiple-image upload system using PHP and MySQL. The system will enable users to upload, verify and display images on your website in a user-friendly format.
let’s dive into the step-by-step implementation of the tutorial with code examples.
Table of Contents
Step 1: Create a Database and Table
First create a new database named multipleimage and a table named images with columns “id“, “name“, and “img“.
Database Name is multipleimage
Table Name is images
CREATE TABLE `images` (
`id` int(5) NOT NULL,
`name` longtext NOT NULL,
`img` longtext NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
Step 2: Creating the Config.file
why to create config.php File?
Creating a “config.php
” file is a common practice in web development. It serves as a central place to store configuration settings, such as database connection details and other environment-specific variables. Here’s why you might want to create a “config.php
” file:
- Centralized Configuration: Instead of scattering your database connection code throughout your application, you can have a single place where you define the connection details. This makes it easier to update the settings in the future without having to hunt down every instance in your code.
- Security: Storing sensitive information like database credentials in a separate file outside the web root (publicly accessible directory) adds a layer of security. This helps prevent accidental exposure of sensitive information in case of a misconfiguration or security vulnerability.
- Ease of Maintenance: If you ever need to change your database credentials, server name, or any other configuration setting, you only need to update the “
config.php
” file rather than modifying multiple instances of the connection code throughout your application. - Collaboration: When working in a team, having a “
config.php
” file simplifies collaboration. Team members can easily share the same configuration settings without needing to manually update each other’s code. - Code Readability: By separating configuration from the rest of your code, your code becomes more readable and focused on the application’s logic rather than configuration details.
Here’s an example of what a “config.php
” file might look like this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "multipleimage";
// Create connection
$conn = mysqli_connect($servername, $username, $password,$db);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
?>
You would then include this file at the beginning of your other PHP files that need to interact with the database:
<?php
include 'config.php';
?>
This way, you can simply update the connection details in one place (the “config.php
” file) if they ever change, all your application files will automatically use the updated settings.
Step 3: Creating the HTML Form
- Set up the basic HTML structure with a form element.
- Add input fields for users to enter image names and select multiple images for upload.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>multipleimage</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<label for="catname">Name</label>
<input name="name" type="text" class="form-control" id="catname" placeholder="Name" required>
<br>
<label for="metadescription">Multipleimage Upload</label> <br>
<input type="file" class="form-control upload-btn" placeholder="File" name="img[]" id="attach" multiple/>
<br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Step 4: Styling the Form
- Use CSS to style the form, making it visually appealing and user-friendly.
- Apply responsive design principles to ensure the form looks good on various devices.
<style>
body {
font-family: Arial, sans-serif;
}
form {
max-width: 400px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
background-color: #f9f9f9;
border-radius: 5px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input[type="text"], input[type="file"] {
width: 95%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
input[type="submit"] {
background-color: #007bff;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #0056b3;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
img {
padding: 5px;
max-width: 100px;
max-height: 100px;
padding: 10px;
}
</style>
Step 5: PHP Backend – Handling Image Uploads
- Use PHP to process the form submission.
- Retrieve the uploaded image files and their details using the “
$_FILES
” superglobal. - Loop through the uploaded files, validating each one.
- Check if the file is an actual image using the “
getimagesize()
” function.
Step 6: Uploading Images to the Server:
- Create a directory on your server to store uploaded images.
- Move the validated image files to the appropriate directory using the “
move_uploaded_file()
” function.
Step 7: Inserting Data into the Database:
- Establish a connection to your MySQL database using the “
mysqli
” functions. - Insert the image data (image paths and names) into the database table.
- Handle errors if the insertion process fails.
//Insert Multiple-Image
<?php
// Check if the form is submitted
if (isset($_POST['submit'])) {
// Retrieve form data
$name = $_POST['name'];
$filenames = $_FILES['img']['name'];
$tmp_names = $_FILES['img']['tmp_name'];
$folder = [];
$flagUnsupportedFormat = false; // Flag to track unsupported formats
// Loop through each file and move it to the respective folder
foreach ($filenames as $key => $filename) {
$tmp_name = $tmp_names[$key];
$folder[] = "uploads/" . $filename;
// Check if the file is an image
$check = getimagesize($tmp_name);
if ($check === false) {
echo "File '$filename' is not an image.<br>";
continue; // Skip this file and move to the next
}
// Check file format
$allowedFormats = ["jpg", "jpeg", "png", "gif","webp"];
$imageFileType = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (!in_array($imageFileType, $allowedFormats)) {
echo "File '$filename' has an unsupported format. Only JPG, JPEG, PNG, and GIF files are allowed.<br>";
$flagUnsupportedFormat = true; // Set the flag
continue; // Skip this file and move to the next
}
// Check file size (optional, set your desired size)
$maxFileSize = 5 * 1024 * 1024; // 5MB
if ($_FILES['img']['size'][$key] > $maxFileSize) {
echo "File '$filename' is too large. Maximum size allowed is 5MB.<br>";
continue; // Skip this file and move to the next
}
move_uploaded_file($tmp_name, $folder[$key]);
}
if (!$flagUnsupportedFormat) {
// Insert data only if no unsupported formats were encountered
$sql = "INSERT INTO images2 (img, name)
VALUES ('" . implode(",", $folder) . "', '$name')";
if ($conn->query($sql) !== TRUE) {
echo "Error inserting record: " . $conn->error;
}
}
}
?>
Step 8: Displaying Uploaded Images:
- Retrieve image data from the database using SQL queries.
- Loop through the retrieved records and extract image paths and names.
- Display images on your webpage using the”
<img>
” tags, setting the “src
” attribute to the image paths.
<?php
// Display MultipleImages
// Retrieve data from the table
$sql = "SELECT * FROM images2";
$result = $conn->query($sql);
$i = 1;
if ($result->num_rows > 0) {
// Output the data in a table format
echo "<table class='table'>
<tr>
<th>Id</th>
<th>Name</th>
<th>Image</th>
</tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr>
<td>" . $i . "</td>
<td>" . $row["name"] . "</td>
<td>";
// Split the image paths by comma
$imagePaths = explode(",", $row["img"]);
// Loop through the image paths and display the images
foreach ($imagePaths as $imagePath) {
echo "<img src='" . $imagePath . "' alt='Image' width='100' height='100'>";
}
echo "</td></tr>";
$i++;
}
echo "</table>";
} else {
echo "No data found";
}
// Close the database connection
$conn->close();
?>
Conclusion:
By following these code examples and explanations, you’ll be able to create a multiple-image upload system using PHP and MySQL. Remember to adapt the code to fit your project’s needs and ensure proper security measures, such as validating and sanitizing user input. With this system in place, you’ll empower your website’s users to upload and showcase multiple images seamlessly.
Full Code:
<?php
include'connection.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>multipleimage</title>
<style>
body {
font-family: Arial, sans-serif;
}
form {
max-width: 400px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
background-color: #f9f9f9;
border-radius: 5px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input[type="text"], input[type="file"] {
width: 95%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
input[type="submit"] {
background-color: #007bff;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #0056b3;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
img {
padding: 5px;
max-width: 100px;
max-height: 100px;
padding: 10px;
}
</style>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<label for="catname">Name</label>
<input name="name" type="text" class="form-control" id="catname" placeholder="Name" required>
<br>
<label for="metadescription">Multipleimage Upload</label> <br>
<input type="file" class="form-control upload-btn" placeholder="File" name="img[]" id="attach" multiple/>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
// Check if the form is submitted
if (isset($_POST['submit'])) {
// Retrieve form data
$name = $_POST['name'];
$filenames = $_FILES['img']['name'];
$tmp_names = $_FILES['img']['tmp_name'];
$folder = [];
$flagUnsupportedFormat = false; // Flag to track unsupported formats
// Loop through each file and move it to the respective folder
foreach ($filenames as $key => $filename) {
$tmp_name = $tmp_names[$key];
$folder[] = "uploads/" . $filename;
// Check if the file is an image
$check = getimagesize($tmp_name);
if ($check === false) {
echo "File '$filename' is not an image.<br>";
continue; // Skip this file and move to the next
}
// Check file format
$allowedFormats = ["jpg", "jpeg", "png", "gif","webp"];
$imageFileType = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (!in_array($imageFileType, $allowedFormats)) {
echo "File '$filename' has an unsupported format. Only JPG, JPEG, PNG, and GIF files are allowed.<br>";
$flagUnsupportedFormat = true; // Set the flag
continue; // Skip this file and move to the next
}
// Check file size (optional, set your desired size)
$maxFileSize = 5 * 1024 * 1024; // 5MB
if ($_FILES['img']['size'][$key] > $maxFileSize) {
echo "File '$filename' is too large. Maximum size allowed is 5MB.<br>";
continue; // Skip this file and move to the next
}
move_uploaded_file($tmp_name, $folder[$key]);
}
if (!$flagUnsupportedFormat) {
// Insert data only if no unsupported formats were encountered
$sql = "INSERT INTO images2 (img, name)
VALUES ('" . implode(",", $folder) . "', '$name')";
if ($conn->query($sql) !== TRUE) {
echo "Error inserting record: " . $conn->error;
}
}
}
?>
<?php
// Display MultipleImages
// Retrieve data from the table
$sql = "SELECT * FROM images2";
$result = $conn->query($sql);
$i = 1;
if ($result->num_rows > 0) {
// Output the data in a table format
echo "<table class='table'>
<tr>
<th>Id</th>
<th>Name</th>
<th>Image</th>
</tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr>
<td>" . $i . "</td>
<td>" . $row["name"] . "</td>
<td>";
// Split the image paths by comma
$imagePaths = explode(",", $row["img"]);
// Loop through the image paths and display the images
foreach ($imagePaths as $imagePath) {
echo "<img src='" . $imagePath . "' alt='Image' width='100' height='100'>";
}
echo "</td></tr>";
$i++;
}
echo "</table>";
} else {
echo "No data found";
}
// Close the database connection
$conn->close();
?>
</body>
</html>