In our previous blog we taught you about how to upload images using jQuery and PHP but it works for single image. Now, In this blog post we focused on Multiple Image uploading functionality using PHP and jQuery in forms. Just click on live demo or follow our codes to use it.
Here, we have created an html form, set it’s attribute enctype=”multipart/form-data”. This form contains input tag , type=” file” when a user clicks on this input tag a window will opens for image file selection, after image selection an image preview is shown to user (using jquery).
Also, there is an Add More Files button which allows user to dynamically create above input tag, type=” file” and with it he/she can perform the same functionality as explained above.
As user clicks on another input tag of type submit on which a PHP script will executes in which we wrote our codes in following steps:-
- We defined an array of allowed extensions .
$validextensions = array("jpeg", "jpg", "png");
- Defined a variable to store the selected file extension.
$ext = explode('.', basename($_FILES['file']['name'][$i]));//Explode file name from dot(.)
$file_extension = end($ext); //Store extensions in the variable
- Matching selected file size and it’s extension with allowed file size and allowed file extensions.
if (($_FILES["file"]["size"][$i] < 100000) // Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
//PHP Image Uploading Code
}
- If it is invalid file then,
echo "<span>***Invalid file Type or file Size Exceeded***<span>";
- Else the following code will execute:
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) { // If File Moved To Uploads Folder
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/>';
} else { // If File Was Not Moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/> ';
}
} else { // If File Size And File Type Was Incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
HTML Form : multiupload.php
We have explained line by line process in the above section , Here we have Created a form with html syntax.
<!DOCTYPE html>
<html>
<head>
<title>Upload Multiple Images Using jquery and PHP</title>
<!-------Including jQuery from Google ------>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="script.js"></script>
<!------- Including CSS File ------>
<link rel="stylesheet" type="text/css" href="style.css">
<body>
<div id="maindiv">
<div id="formdiv">
<h2>Multiple Image Upload Form</h2>
<form enctype="multipart/form-data" action="" method="post">
First Field is Compulsory. Only JPEG,PNG,JPG Type Image Uploaded. Image Size Should Be Less Than 100KB.
<div id="filediv"><input name="file[]" type="file" id="file"/></div>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<input type="submit" value="Upload File" name="submit" id="upload" class="upload"/>
</form>
<!------- Including PHP Script here ------>
<?php include "upload.php"; ?>
</div>
</div>
</body>
</html>
PHP Image Uploading Script : upload.php
Here, We have given complete Multiple Image Uploading Script.
<?php
if (isset($_POST['submit'])) {
$j = 0; // Variable for indexing uploaded image.
$target_path = "uploads/"; // Declaring Path for uploaded images.
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
// Loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); // Extensions which are allowed.
$ext = explode('.', basename($_FILES['file']['name'][$i])); // Explode file name from dot(.)
$file_extension = end($ext); // Store extensions in the variable.
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1]; // Set the target path with a new name of image.
$j = $j + 1; // Increment the number of uploaded images according to the files in array.
if (($_FILES["file"]["size"][$i] < 100000) // Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
// If file moved to uploads folder.
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else { // If File Was Not Moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else { // If File Size And File Type Was Incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
jQuery Code: script.js
This, jquery code is to provide image preview facility in form, before Uploading it.
var abc = 0; // Declaring and defining global increment variable.
$(document).ready(function() {
// To add new input file field dynamically, on click of "Add More Files" button below function will be executed.
$('#add_more').click(function() {
$(this).before($("<div/>", {
id: 'filediv'
}).fadeIn('slow').append($("<input/>", {
name: 'file[]',
type: 'file',
id: 'file'
}), $("<br/><br/>")));
});
// Following function will executes on change event of file input to select different file.
$('body').on('change', '#file', function() {
if (this.files && this.files[0]) {
abc += 1; // Incrementing global variable by 1.
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd" + abc + "' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd" + abc).append($("<img/>", {
id: 'img',
src: 'x.png',
alt: 'delete'
}).click(function() {
$(this).parent().parent().remove();
}));
}
});
// To Preview Image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name) {
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
CSS File: style.css
Styling HTML Elements.
@import "http://fonts.googleapis.com/css?family=Droid+Sans";
form{
background-color:#fff
}
#maindiv{
width:960px;
margin:10px auto;
padding:10px;
font-family:'Droid Sans',sans-serif
}
#formdiv{
width:500px;
float:left;
text-align:center
}
form{
padding:40px 20px;
box-shadow:0 0 10px;
border-radius:2px
}
h2{
margin-left:30px
}
.upload{
background-color:red;
border:1px solid red;
color:#fff;
border-radius:5px;
padding:10px;
text-shadow:1px 1px 0 green;
box-shadow:2px 2px 15px rgba(0,0,0,.75)
}
.upload:hover{
cursor:pointer;
background:#c20b0b;
border:1px solid #c20b0b;
box-shadow:0 0 5px rgba(0,0,0,.75)
}
#file{
color:green;
padding:5px;
border:1px dashed #123456;
background-color:#f9ffe5
}
#upload{
margin-left:45px
}
#noerror{
color:green;
text-align:left
}
#error{
color:red;
text-align:left
}
#img{
width:17px;
border:none;
height:17px;
margin-left:-20px;
margin-bottom:91px
}
.abcd{
text-align:center
}
.abcd img{
height:100px;
width:100px;
padding:5px;
border:1px solid #e8debd
}
b{
color:red
}
Conclusion:
This was all about multiple image uploading using PHP and jQuery. Similarily, you can define other file extensions to upload them, just copy or download our codes to use it, keep following us for upcoming blogs.
86 Replies to “Upload Multiple Images Using PHP and jQuery”
It is nice file upload tutorial
Thanks for your appreciation !
Keep reading our other blog posts :
https://www.formget.com/blog/
this is awsom code
thank you sooooooooooooooooooooooooooooooo much for such a great code
and it is easy to use thnxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx admin
thanks sir ,
It was really helpfull for me . to complete my project ,
its great ………………….tanks a lot to your complete team formget.com..
Is this free to use for commercial purposes? Thank you
Yes, You can use this for commercial purpose.
thanks lot for this tutorial. this is most helpful to me. thanks once again formget team 🙂
gracias!!!!
WooooooooooooooooW…. it is awesome work…..
Can I know how to upload these file to a database and how to retrieve those uploaded files in a single HTML page ????
hey admin,
how can i add a line of code to prevent uploading more than, say 3 files?
this code is very helpful for me ……..great post
Thanks for your appreciation !
Keep reading our other blog posts.
https://www.formget.com/blog/
If i select Multiple image by adding this line of code : “”, then i should all the images preview. How can i do so??
Thanks for FormGet for such an app.
I have a doubt…….
From the above code, i’m selected few photos at once. I want preview for those images.
How can i do so???
very good tutorial. All files are directly working in my Laptop after downloading from your webpage. Thanks a lot
hey, how can i display images side by side, instead of one below another?
WooooooooooooooooW…. it is awesome work…..
Hello,
Your tutorial is fantastic. It solved my problem. But, now I need your help on further implement.
I have saved images in database using this code. Now, I want to preview images after fetching from database.
Can you please help me out on this?
Thank You
Dear sir/ ma’am
multi pal image uploading this code is very helpful for me
but sir i can’t able to insert image in mysql data base
can you sent me code please i have insert and fetch image through data base
and revert mail me as soon as possible i need so much this code for my website
[email protected]
thank you
Thanks bro…
this is nice…i’ll use it for my project..
this is a nice tutorial
Thank you so much to all for reading our blogs…!
keep visiting for catching up new posts.
https://www.formget.com/blog/
sir.. can give the suitable db for upload multiple image. Im newbie here. need learn more for my FYP. Thanks.
Did you ever figure out how to put them side by side?
hii admin
i also want to mail the uploaded images to some
is it possible??
Thanks in advance
plzz reply its urgent
Can you figure out:- how i can show preview side by side
Im having troubles with this form. Leave it to me the non PHP programmer to mess it up..
Only thing I changed was the $target_path = “/uploads” to $target_path = “../images/project-pictures”
Here are my details.
The files in this blog were created in a sub directory named “Projectmanager” and my images folder is one directory back in my root.
Therefore the actual path to my folder Im trying to write the files into is “http://mysite.com/images/project-pictures/”
The actual folder to the upload files to do this whole process is “http://mysite.com/projectmanager/multipleuploads.php
I have set my folder permission where Im trying to upload the files to “777”
PHP Gods what have I done?
My apologies my error is:
Warning: move_uploaded_file(uploads/80387c7178100469ce3406bcf0970496.gifb43281c26a8dbbc3c8907ebedd873977.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in /homepages/6/d437176804/htdocs/mysite/Projectmanager/upload.php on line 14
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move ‘/tmp/php2gJ11v’ to ‘uploads/80387c7178100469ce3406bcf0970496.gifb43281c26a8dbbc3c8907ebedd873977.jpg’ in /homepages/6/d437176804/htdocs/mysite/Projectmanager/upload.php on line 14
2).please try again!.
nice tutorial but there is an error if you will upload more than 6 image at one upload
you’re right i hope they can fix that
Just change the upload php code to this
$name) {
if ($_FILES[‘files’][‘error’][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES[‘files’][‘error’][$f] == 0) {
// No error found! Move uploaded files
if(move_uploaded_file($_FILES[“files”][“tmp_name”][$f], $path.$name))
$count++; // Number of successfully uploaded file
}
}
}
?>
The reason for the error is because the code is appending a new image name every time more than one image is added. When more than 6 images are added the image file name becomes too long and there for the error.
Thank you..
Great upload file tutorial….
Hello,
Great Work, How i can add other type of file to upload, like PSD (photoshop), AI (Illustrator)….and other type of file ?
May you please guide me to implement it in your code ?
Thanks,
Arshi
Hi this is perfect image uploader.
Hi, nice tutorial, but i just wanna know, how to make thumbanli list horizontal?
iam new in coding, hope become expert like you.
😀
good morning
works very well, but I have a problem, when I delete an image, it does not add me the right to add a picture ??? please help my tanks
Thanks man, this is very nice script. I was searching it for weaks!! Thank you again:)
its really nice code for uploading multiple files in folder…….
Awesome code for uploading and nice site and view design…
wow!! what a code
Float image left and resize. But wlth JQMobile only the first image loads. I can’t add images neither delete
thanks, i love the way you explain codes…
how can i limit the number of uploads to maximum 3 files and save the path of those images in database in same row
Use this
$(“#add_more”).click(function(){
var $btn = $(this);
var count = ($btn.data(“click_count”) || 0) + 1;
$btn.data(“click_count”, count);
if ( count <= 4 ){
$(this).before($("”, {
id: ‘filediv’
}).fadeIn(‘slow’).append($(“”, {
name: ‘file[]’,
type: ‘file’,
id: ‘file’
}), $(“”)));
}else {
$btn.text(“third and final click”);
$btn.unbind(“click”);
$(“#add_more”).hide();
}
return false;
});
Thanks !!! It helped a lot ..
Error in your code: this line
$target_path = $target_path . md5(uniqid()) . “.” . $ext[count($ext) – 1]; // Set the target path with a new name of image.
when run (inside the loop) will make a filename that includes the target_path and duplicates it. So the second file name will be the name of the first file plus the name of the second file. third file name will be file1+file2+file3.
To fix, set the upload path thusly:
$upload_path = “uploads/”;
Then set the target path
$target_path = $upload_path . md5(uniqid()) . “.” . $ext[count($ext) – 1]; // Set the target path with a new name of image.
Other than that (which took me a few hours to figure out), nice script; works quite well.
..Rick…
Thanks sir.
thanks..
Thank you so much for this! It’s flawless!
It’s really helpful. Thanks a lot.
This is very good site.. thanks for your nice tutorials..
Nice Coding. how to write insert query in your upload.php.
Any one ever figure out how to put the images side by side. Been working on the css for 2 hours now with no success.
For those still trying to make it horizontal, here’s the solution. The place to change is this:
var abc = 0; // Declaring and defining global increment variable.
$(document).ready(function() {
// To add new input file field dynamically, on click of “Add More Files” button below function will be executed.
$(‘#add_more’).click(function() {
$(this).before($(“”, { // ********the problem is here *******/
id: ‘filediv’
….
Add a class name to this and use float or display: inline-block to make it horizontal.
$(‘#add_more’).click(function() {
$(this).before($(“”, {
//and the imageview css could look something like
.imageview{
width:150px;
float: left;
}
Note: if you still face a problem with the buttons getting in the way, you can add an extra div on the buttons like this:
Then change the jquery code like so:
$(‘#add_more’).click(function() {
$(‘#add_more_holder’).before($(“”, { // I changed ‘this’ to ‘#add_more_holder’
Finally, go to css and put this in:
#add_more_holder{
border: 2px solid blue;
clear: left;
} //this makes sure no images come down to the buttons.
Sorry, seems like all html code was remove from the code. Should give you an idea though. Just add a class to the div on line 6 and set it to float.
Hi,
I wanna to know,
can each file name has different name?
lets say:
i want to upload 2 images,
image 1 name ( date + random + son )
image 2 name ( date + random + mom )
so in folder upload will have 2 image with 2 file name also in when it save to database,
i try to using jquery dropzone it fail.
please let me know ,
sorry for my bad english
I tried to find this code for long time. It’s the most suitable for my application. Thanks a lot.
Hello PCBA,
Pleased with your appreciation. Keep reading our other blog posts.
Regards,
FormGet Team
My upload folder located at C:\inetpub\wwwroot\multiple_image_upload\uploads. where should I declare the path this script?
Thank bro…………. Please how do I echo the images? and do I insert them into my databse
See my post on stacko
http://stackoverflow.com/questions/31454532/mysql-insert-multiple-images-with-a-prepared-statement
However when image is deleted the image path still inserts into the database.
And also when data is selected from database and form images has to be removed, I still have to find the solution. Please any help on this and thanks upfront
Hello ! THanks for your Upload Multiple Images Using PHP and jQuery ! It works perfectly well..
But i have one little issue ! when i want to load a picture bigger than 11Mo (yes it’s big…) it juste doesn’t work !
i try to set the limite to 1024Mo in php.ini file, and set this 2 line at the begening:
ini_set(‘memory_limit’, ‘1024M’);
set_time_limit(600);
But nothing… when the images are too big it do nothing !
Thanks if you want help, sorry !
I have combined this script to allow a user to insert a comment and send an email with that comment. How could I include a link to this uploaded image in the email?
great tutor, i like it
I want to remove click button (#addmore), so when i add 1 image, it will automate create new input file property without button clicked.
see : https://jsfiddle.net/5orfqhsg/
but, I’m stuck here, when i click del icon to delete the image, the image has removed but input property belong the image still exist, and the result all image’s file post by submit include the delete’s image.
Could you help me to modify this javascript like i want, please?
thank you so much…..pls how can i modify it to upload videos and pdf
sorry sir actually i misunderstands your code. now i feel very comfortable.and i used it for storing image into the database thank you so much
Thank you so much, this works like charm!
please do you know how I can echo the images from database path?
please how do I echo the images from my database path ? I really need your help
thanks
What part of the code would need to be changed to not use the temp name for the image, but rather the name of the image itself. Thanks.
when i remove a file then the preview of that image is removed from there but it store in datdabase what to any suggestion
I want to increase image size i want to upload 10 mb image how i increase this size
but for a live website, how can I use this function? your code is uploading on a folder. for website, there needs to store also database & show on webpage. Can you please instruct or send codes for website using of this function?
thank you sooo much for such a great code . but
how to save in database.
i want to upload the images to my sql database in php myadmin.
need help please.
please suggest some code which works with the above.
it”s so nice,
i just ask a Qus. that how many column create in table for image upload ….?
Hello.This post was really motivating, especially because I was looking for
thoughts on this topic last Monday.
fantastic points altogether, you simply won a new reader.
What could you suggest iin regards to your submit that you simply made a few
days ago? Any positive?
I believe this site hhas got some real wonderful information for everyone :D.
thankyou so much. its simple and perfect
You ought to take part in a contest for one of the
greatest websites on the net. I most certainly will recommend this
site!
Thank youu for all of the lbor on this site. My daughter enjoys managing investigations and it is simple
to grasp why. We learn all regarding the powerful tacric
you give useful information through your blog and as well recommend participation from
visitors on this article so my girl is actually becoming educated a lot of things.
Enjoy the rest of the year. Yoou are always doing a fabulous job.