File upload in PHP is the most used functionality for the web application. A single file or multiple files can be easily uploaded using PHP. PHP provides a quick and simple way to implement server-side file upload functionality. Generally, in the web application, the file is uploaded to the server and the file name is stored in the database. Later the files are retrieved from the server based on the file name stored in the database.
In most cases, a single image is uploaded at once. But sometimes you have a requirement to upload multiple images at once. In this tutorial, we will show you how to upload multiple images in PHP and store the images in the MySQL database. Multiple image upload allows the user to select multiple files at once and upload all files to the server in a single click.
Our example code will implement the following functionality to demonstrate the multiple images upload in PHP.
A table needs to be created in the database to store the image file names. The following SQL creates an images
table with some basic fields in the MySQL database.
CREATE TABLE `images` ( `id` int(11) NOT NULL AUTO_INCREMENT, `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `uploaded_on` datetime NOT NULL, `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The dbConfig.php
file is used to connect and select the MySQL database. Specify the database hostname ($dbHost
), username ($dbUsername
), password ($dbPassword
), and name ($dbName
) as per your MySQL credentials.
<?php
// Database configuration
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "codexworld";
// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>
Create an HTML form with an input field to allow the user to select images they want to upload.
The <form> tag must contain the following attributes.
The <input> tag must contain type="file"
and multiple
attributes.
<form action="upload.php" method="post" enctype="multipart/form-data"> Select Image Files to Upload: <input type="file" name="files[]" multiple > <input type="submit" name="submit" value="UPLOAD"> </form>
The upload.php
file handles the multiple image upload functionality and shows the upload status to the user.
<?php
// Include the database configuration file
include_once 'dbConfig.php';
if(isset($_POST['submit'])){
// File upload configuration
$targetDir = "uploads/";
$allowTypes = array('jpg','png','jpeg','gif');
$statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = '';
$fileNames = array_filter($_FILES['files']['name']);
if(!empty($fileNames)){
foreach($_FILES['files']['name'] as $key=>$val){
// File upload path
$fileName = basename($_FILES['files']['name'][$key]);
$targetFilePath = $targetDir . $fileName;
// Check whether file type is valid
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
if(in_array($fileType, $allowTypes)){
// Upload file to server
if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath)){
// Image db insert sql
$insertValuesSQL .= "('".$fileName."', NOW()),";
}else{
$errorUpload .= $_FILES['files']['name'][$key].' | ';
}
}else{
$errorUploadType .= $_FILES['files']['name'][$key].' | ';
}
}
// Error message
$errorUpload = !empty($errorUpload)?'Upload Error: '.trim($errorUpload, ' | '):'';
$errorUploadType = !empty($errorUploadType)?'File Type Error: '.trim($errorUploadType, ' | '):'';
$errorMsg = !empty($errorUpload)?'<br/>'.$errorUpload.'<br/>'.$errorUploadType:'<br/>'.$errorUploadType;
if(!empty($insertValuesSQL)){
$insertValuesSQL = trim($insertValuesSQL, ',');
// Insert image file name into database
$insert = $db->query("INSERT INTO images (file_name, uploaded_on) VALUES $insertValuesSQL");
if($insert){
$statusMsg = "Files are uploaded successfully.".$errorMsg;
}else{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$statusMsg = "Upload failed! ".$errorMsg;
}
}else{
$statusMsg = 'Please select a file to upload.';
}
}
?>
Upload Multiple Files and Images in CodeIgniter
Now we will retrieve the file names from the database and display the respective images from the server on the web page.
<?php
// Include the database configuration file
include_once 'dbConfig.php';
// Get images from the database
$query = $db->query("SELECT * FROM images ORDER BY id DESC");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$imageURL = 'uploads/'.$row["file_name"];
?> <img src="<?php echo $imageURL; ?>" alt="" /> <?php }
}else{ ?>
<p>No image(s) found...</p>
<?php } ?>
Create Dynamic Image Gallery with jQuery, PHP & MySQL
Here we have shown the easiest way to integrate multiple image upload functionality on the website. This example code also is used to upload multiple files in PHP. You can extend these multiple image upload functionality as per your needs. For user-friendly image upload, you can implement Drag and drop file upload using Dropzone JS and PHP. Alternatively, the Ajax multiple images upload will provide a better user-interface to the website.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
hI Thanks,
how to randomly rename the images ?
thanks it was simple and clear.. 🙂
Easy and usefull code!!
Thanks!!
u saved my day, thank u (y)
Thank you very much its working
Hi, Your code very much useful for me , Its working fine , Thank you for your wonderful job
Hi! Thanks a lot for the code it helped me a lot and I’m just getting started with PHP. I’m working on a hobby project and I’ve been trying to add something like a “batch id” that I can manually input in the form upon uploading the images but I just can’t seem to get it right, is there any other example I can look at?
Thanks a lot!
Ev.
Kevin make user ID i.e Bob’s ID from the user table a foreign key in the image table by adding another column. You can then get images by the user ID;
how to fetch uploaded image in slider
Is the status column in the table necessary? I don’t see where it’s used in the rest of the code, aside from defaulting to one if an entry is created.
No, the status field is not necessary. But, it will be useful for the functionality extension in the future.
Your code just worked fine. Thank you. i have a question,
how if i upload 3 photo with 1 user ?
example :
name | photo
Bob | beach.jpg, home.jpg, toilet.jpg
sorry my bad english.
Your code just worked fine. Thank you.
Hey, Thank you very much. I am in a hurry for my project. Your code works very smooth in the first time of launch. Save a lot of time. Good work. Keep It up.
Hi. Your code snippet really helped my problem. Continue doing good work. Thank you.