Sometimes we need to allow our users to upload multiple file upload. On my previous post I was shown the basic of simple file upload with PHP. Today I am going to show you how to allow users to upload multiple files. It is almost similar like simple file upload but we need to do some modification with html markup and php code. multiple attribute is needed to add on the html markup. Major web browsers like Firefox, Chrome, Safari and IE 9+ support this attribute. Now I am going to show you how to upload multiple file with PHP and basic HTML form.
Live Demo Download Source
HTML Markup
Take a look at the html markup bellow. We need to add a simple html form with input type file and submit property. We also need to give file input type file name with box breaks like files[] and need to add a property named multiple. Here accept is an optional property that used to allow users to upload only image files.
<html lang="en"> <head> <meta charset="UTF-8" /> <title>Multiple File Ppload with PHP</title> </head> <body> <form action="" method="post" enctype="multipart/form-data"> <input type="file" id="file" name="files[]" multiple="multiple" accept="image/*" /> <input type="submit" value="Upload!" /> </form> </body> </html>
PHP Script
This php code handles uploaded files and save to the server.
$valid_formats = array("jpg", "png", "gif", "zip", "bmp"); $max_file_size = 1024*100; //100 kb $path = "uploads/"; // Upload directory $count = 0; if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){ // Loop $_FILES to exeicute all files foreach ($_FILES['files']['name'] as $f => $name) { if ($_FILES['files']['error'][$f] == 4) { continue; // Skip file if any error found } if ($_FILES['files']['error'][$f] == 0) { if ($_FILES['files']['size'][$f] > $max_file_size) { $message[] = "$name is too large!."; continue; // Skip large files } elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){ $message[] = "$name is not a valid format"; continue; // Skip invalid file formats } else{ // No error found! Move uploaded files if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name)) $count++; // Number of successfully uploaded file } } } }
very good
ReplyDeleteThis comment has been removed by the author.
DeleteSimple and easy!
ReplyDeleteAnyone know why it would be saving some sort of array file instead of the actual files?
ReplyDeleteChange max_file_uploads value on you php.ini file. By Default it is 20. You can increase as much as you want.
Deletebut where is the php.ini file anyway? I don't understand how to control the file size as well. please help. thank you
Deletein your www directory or htdocs you will found php folder and in php folder you can easily find out php.ini file
DeleteBest code on the web!!
ReplyDeleteStraight to the point
Thank you
this code is uploading files in a folder, but i want to upload files in mysql database and then fetch those files with particular ID.
ReplyDeleteHave you found an answer to your question yet? Because I'm also looking for this kind of code...
DeleteBest regards, Sem
save the link to file in database table. You can not save files to database.
DeleteActually that is not correct "Anonymous"
DeleteTry to take a look at the BLOB fields
heres a little list of how much data the different types can keep.
TINYBLOB - 255 bytes
BLOB - 65535 bytes
MEDIUMBLOB - 16,777,215 bytes (2^24 - 1)
LONGBLOB - 4G bytes (2^32 – 1)
they store data binary lets take a little example while we are at it.
$saveImage = file_get_contents('/path/to/image/image.jpg');
mysql_query('INSERT INTO images (picture) VALUES ("' . mysql_real_escape_string($saveImage) . '")');
The rest is up to you, however it is a slow process if you compare it just uploading it to your webserver
and storing the link in the database.
Very good thanks a lot...
ReplyDeleteThanks a lot. Is it possible to automaticly rename the files, because files from different users may have the same names? (sorry for my bad english, i'm french speaking:)
ReplyDeleteYap! You can save your files with unique file name with uinqid().
Delete// get original extension
$ext = pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION);
// create new unique file name with extension
$uniq_name = uniqid() . '.' .$ext;
You can also take a look at this example's php section.
$ext = pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION);
Delete$uniq_name = uniqid() . '.' .$ext;
i am new to php.
please tell me where to add the above php code to get unique name. also i want to add the unique number with the php original file name. please send me the script to muthubalaji90@gmail.com
Replace this line:
Deletemove_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name);
to:
$ext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);
$uniq_name = uniqid() . '.' .$ext;
move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path . $uniq_name);
hi i am also new in PHP can you help me make upload like this web http://postimage.org/index.php?um=web. Upload much image just paste url by per line. Please help me
Delete@admin
DeleteGet this source from http://www.w3bees.com/2013/09/download-file-from-remote-server-with.html
// explode all lines
$lines = explode("\n", $data);
foreach ($lines as $line) {
download($line);
}
thank you very much
DeletePlease check your google+
Deletehi...
ReplyDeletegood example.But, i want to ask how to upload multiple file to ftp?as your answer above we can use property "multiple" in the form.But,i don't know to do the looping process and where i have to put the "ftp_put" parameter....
Hope you can help me with full example of coding.
Your help is really appreciated
DeleteHello,
ReplyDeletethank you very much for this script.
It works fine but is this possible to make simple a loading image for upload.
i think its easyer to see for users.
sorry for my bat english i'm german.
Sorry I do not get you! What do you mean? preview before upload or else? Please clearly...
DeleteHmm.. i try it.
DeleteIf i upload any file i need to see an loading gif-image like here: http://www.sky-tours.com/images/loading.gif
hope you understand me
For better understanding.
DeleteI mean - File Upload with only one progress bar or animate gif image like in my post below
Best regards Wolfgang
HI! I'm Gianluca from Italy! Great Resalat Haque, how can we load directory - sub_directory and file tree in the same order and save routes in mysql We found webkitdirectory HTML5, but does not load entire folder structure ...? only files and not recursively ... We searched all over the web, but ... nothing ... can you help us?
ReplyDeleteHi guy!
ReplyDeleteVery good example, easy, fast and completely useful!
I have modified to save files in random folders and I have added other script as well, to compress in one zip file, you know trying to make a simple we-transfer for local use.
But, could you give me any tip to make your script valid to uploads files from different folders?
I have done it showing various lines to select files, but you knnow, it's quite 'dirty'...
What I'm looking for is that only when I have added some files, only then, show another line/button to add more files.
Later I will try to discover how to show a progress bar...
Anyway, many many thanks!!!! I really appreciate your work, THANK YOU!
what framework did you use? is it CodeIgniter? and what type of database storage did you use? can I use wamp or oracle? pls. reply... i just badly need it... btw I'm just a student and I'm hoping that you can really help me with this. because it is part of my requirements as my project to graduate. :) thank you and God Bless
ReplyDeleteThanks for your very simple & easy script.
ReplyDeleteI've uploaded an image the dimension is 437*656, then re-sized into 460*305. The result was only half of the image is re-sized! What to do to get the full image re-sized?
Hi, im trying to send the file names via email but not sure how to send it any ideas?
ReplyDeleteCan u please tell me how to insert the file path into mysql database..?
ReplyDeleteAs you already know where your storing your data on your webserver
Deleteall you really need to do is make a query to your database with the path information and image name
$image = "imagename.png"
$sql = "INSERT INTO DB_NAME (path) VALUES('/path/to/your/$image')";
mysql_query($sql);
nothing speciel there however you might want to sanatize the data
Hi everyone, this is a very nice script.
ReplyDeletebut I keep getting an error when running it:
Warning: Invalid argument supplied for foreach()
he gives this error on line "foreach ($_FILES['files']['name'] as $f => $name) {"
The error only occurs on multiple files, not on a single file.
Anyone any suggestions?
thanks
Very nice and useful :)
ReplyDeleteThe images gets uploaded but it shows as invalid image when i try to open it.. :(
ReplyDeleteplease, anyone help me. I want to save a path (url of file) on a database, but i cant.
ReplyDeleteI modified a little bit the code (http://pastebin.com/KKRw4qfK)
the files are upload correctly, but only one file is inserted into the database
that's the code, everytimes i uploads file only first file is inserted into the database
http://pastebin.com/KKRw4qfK
please help.. I'm a noob with php. :/
sorry for my bad english, i speak spanish
http://stackoverflow.com/questions/21222356/php-multiple-files-upload-and-gets-path-of-each-ones-files-uploads-for-mysql/21222619?noredirect=1#21222619
Deletehere a solution
I am using this script and it works perfect,but i need to echo the url of each uploaded file after it is done .
ReplyDeleteI found a way that works ,then I added the code to change the file names. Now I cant get it to echo the new file name just the old one. I added this code
$ext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);
$uniq_name = uniqid() . '.' .$ext;
move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path . $uniq_name);
When not changing the name I am able to echo the urls with this
}
foreach ($_FILES['files']['name'] as $f => $name)
{
echo "http://www.mysite.com/uploader/uploads/";echo $name; echo"
";
}
How do I make it echo the new name instead of the real file name?
Please help me correct this.
Thank you very much. Simple and straight foreward.
ReplyDeleteSir what code it should be . If I upload a same picture in my folder, I want to have an error pop up to validation. thanks for the answer. :)
ReplyDeleteThanks for your article.
ReplyDeleteVery good thanks a lot.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteYou rock... For preview before Upload , Using HTML5
ReplyDeletehttp://www.html5rocks.com/en/tutorials/file/dndfiles/
I'm really appreciate your work, from cambodia web developer.
ReplyDeletewhen i was trying to upload more than 5 files using this code.i am geting an error like this.
ReplyDeletehow can i over come this problem .please reply its urgent.....
"( ! ) Notice: Undefined index: files in ..\addstaff.php on line 55
Call Stack
# Time Memory Function Location
1 0.0007 411576 {main}( ) ..\addstaff.php:0
( ! ) Warning: Invalid argument supplied for foreach() in C:\wamp\www\qdoc2\addstaff.php on line 55
Call Stack
# Time Memory Function Location
1 0.0007 411576 {main}( ) ..\addstaff.php:0"
How to add individual image description (title - date - etc) in this case? Thanks.
ReplyDeleteThank you for your tutorial
ReplyDeleteHello nice tutorial :D but how can I check the memtype of the file, I already tried with this $_FILES['files']['type'][$f], but it doesn't work.
ReplyDeleteFor exampla If I hava a .exe file and I change de extension to .jpg the file shouldn't be uploaded, how can I do that?
And a second doubt :P how can I count the files before the submit and if they are more than the allowed number of images to upload, just upload what it lefts? For example, it's just allowed to upluad 20 images so if I have 15 registered in my database, if I try to upload 10, it only has to upload 5 and the other 5 not
Thank u :3
Sorry if this is posted twice:
ReplyDeleteThank yo for the tutorial. I am getting this error:
Warning: move_uploaded_file(uploads/TR0789603194.zip): failed to open stream: No such file or directory in /home5/onlinepc/public_html/action/subs/web_intake.php on line 113
Warning: move_uploaded_file(): Unable to move '/home5/onlinepc/public_html/tmp/phpUU8kdx' to 'uploads/TR0789603194.zip' in /home5/onlinepc/public_html/action/subs/web_intake.php on line 113
Line 113 is:
if(move_uploaded_file($_FILES["text_content"]["tmp_name"][$f], $path.$name))
My Path is:
$path = "uploads/";
Also, How can I save each file path in the database to allow easy download on backend?
Nice + easy + WORKING
ReplyDelete#ThankYouVeryMuch
Thank You very much very help full
ReplyDeletehow to upload selected folder on sever by drop down menu
ReplyDeleteget me idea
Hi, when I try to upload more than 4 files at a strech I am getting the following error
ReplyDelete"Warning: Invalid argument supplied for foreach() in C:\wamp\www\multiple-file-upload-with-php\index.php on line 16"
"Notice: Undefined index: files in C:\wamp\www\multiple-file-upload-with-php\index.php on line 16"
What might be the issue?
hello sir;
ReplyDeleteam thanksfull to you for providing such information. your all iformation is much valuable for me and i hope in the future you will launch more information. if anyone feel problem please visit all android software contant and data
Hi
ReplyDeleteAbsolut great script
But need one function, resize of images, could you please add this Option?
Thank you
hi,
ReplyDeleteThe function is good but... $message don't use? no return?
init $message
$message = array();
finally
return ($message)?$message:1;
This comment has been removed by the author.
DeleteMaybe a bit too late since this was posted over a year ago.. But for everyone who wants the message to be displayed:
DeleteYou can't return an array. it should be:
before foreach loop:
$message = array();
in the end before the foreach ends:
$messages = implode("[br]", $messages);
return $messages;
explanation:
the implode() function returns a string from an array. the items get seperated by the "[br]"
[br] should be "<"br">" (this editor executes HTML xd)
hello, thank you for the tutorial...
ReplyDeleteI was wondering, if I want to save the picture name into database with table contains field : dateupload, image1, image2, image3...
I'll try to do it, but somethinug goes wrong, it become 3 rows data, not 1 rows data like I want to... Could you help me, Sir?
I put my code after for each, but I don't know how to store the multiple image name...
$sql = "insert into PIMAGE (dateupload,image1,image2,image3) values (now(),'$name,'$name','$name')";
thank you for the tutorial...
ReplyDeletebut sir how to upload more than 20 images
thanks for sharing. Nice work.
ReplyDeleteI want to inform you that Source file link not working on any tutorial.
Please update source file link.
Thank you
Hello,
ReplyDeleteI would want to know how to make for post my photos uploader, please ?
Thank' for helping
I keep getting an error that tells me 'files' is an undefined index in my php. I can't figure out why not. I've already tried changing the id in the html file from 'file' to 'files'. Any idea how to fix this?
ReplyDeleteHola¡ Como se podrían guardar las imágenes en una BD.
ReplyDeleteGracias
Very good and simple. Thanks!!
ReplyDeleteMuchisimas gracias
ReplyDeleteHello there, would it be possible for you to upload multiple files while resizing them all as well?
ReplyDeletedid you find anything on this?
DeleteI've read 20+ tutorials and yours is the one really work.
ReplyDeleteI just wanna say thank you.
This comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThank you. the above code is working in browser but when i tried this from my mobile i can’t able to upload image more than one(able to upload only one image but i want to upload multiple image). can u able to solve this issue?
ReplyDeletePlz reply
Deletethanks for this code but i have multiple file upload in dynamically on button click plz help me
ReplyDeleteThis comment has been removed by the author.
ReplyDeletePlz reply
ReplyDeleteplease i want to know how to send all files select the imput from the database and the files in their field (URL only)
ReplyDeletelove u borther
ReplyDeletegreat thank you
ReplyDeleteHi. I need to display multiple images by single id of Database and those multiple images are stored in DB. If u favour me so i 'll be thankful
ReplyDeletedich vu ke toan dich vu lam bao cao tai chinh tín
ReplyDeletekhóa học kế toán thực hành re
công ty dịch vụ kế toán
dich vu ke toan thue tai bac ninh
dịch vụ kế toán trọn gói tại hà nội
dịch vụ kế toán tại tp.hcm
dịch vụ báo cáo thuế
dịch vụ quyết toán thuế uy
trung tâm đào tạo kế toán tại tphcm
trung tâm đào tạo kế toán tại cầu giấy tín
trung tâm đào tạo kế toán tại long biên
trung tâm đào tạo kế toán tại hà đông re
trung tâm kế toán tại thanh xuân
trung tâm kế toán tại bắc ninh
trung tâm kế toán tại bình dương
trung tâm kế toán tại hải phòng
dịch vụ quyết toán thuế tại quận bình thạnh
dịch vụ quyết toán thuế tại quận tân phú
dịch vụ quyết toán thuế tại quận 5
dịch vụ quyết toán thuế tại quận 3
dịch vụ quyết toán thuế tại tphcm
dịch vụ quyết toán thuế tại quận cầu giấy
dịch vụ quyết toán thuế tại quận long biên
dịch vụ quyết toán thuế tại quận hà đông
dịch vụ quyết toán thuế tại quận thanh xuân
how to insert filename to database for one column? data will be stored with separate by commas
ReplyDeleteHi everyone, please i am new in this shit, can any body help me on how and where i will create the folder in which the file will be uploaded?
ReplyDeleteThanks in advance.
Hi
ReplyDeleteI am using this script and works perfect but am trying to get a success message display so the user knows they have been uploaded successfully but I keep getting the message repeated based on the number of files I upload, can any one help please
Ian
Sorry forgot to say, I have added the extra code in that makes each file uploaded a unique name, my uploader.php code looks like the following
ReplyDelete$name) {
if ($_FILES['files']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
$ext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);
$uniq_name = uniqid() . '.' .$ext;
move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path . $uniq_name);
$count++; // Number of successfully uploaded file
}
}
}
}
?>
Hi, I am using this script but I encountered error. i don't understand what's the problem . thanks.
ReplyDeleteWarning: move_uploaded_file(uploads/Approved2.png): failed to open stream: Permission denied in /var/www/uploadnesa/uploadtest.php on line 29 Warning: move_uploaded_file(): Unable to move '/tmp/phpvPg9AA' to 'uploads/Approved2.png' in /var/www/uploadnesa/uploadtest.php on line 29
How to add names of picturs in sql ?
ReplyDeleteHow to add names of picturs in sql ?
ReplyDeleteDapatkan disini , karena Obat Pelangsing slimming Capsule Di Apotik belum tersedia , karena slimming capsule tidak di jual di sembarang temapat termasuk di apotik pun tujuannya untuk menjaga ke aslian produk tersebut, karena sekarang banyak perusahaan yang meniru produk produk herbal sehingga herbal yang asli khasiatnya bisa di rusak oleh produk yang palsu. Untuk itu hati hati dengan slimming capsule yang palsu.Slimming capsule yang asli hanya ada di agen herbal tertentu seperti di distro herbal ini, kami merupakan agen herbal terbesar dan sudah di percaya di seluruh penjuru indonesia
ReplyDeletethanks
ReplyDeletethank you
ReplyDeleteHello,
ReplyDeleteFantastisc, it works perfect! But how to get the files directly in the email together with the results..?
Very cool code, is it possible to select more than 300 images at once? Like 8000?
ReplyDeleteThis comment has been removed by the author.
ReplyDeletehttp://devssolution.blogspot.com/2016/07/multiple-files-uploading-using-plupload.html
ReplyDeleteI have read your blog its very attractive and impressive. I like it your blog.
ReplyDeletePHP Training in chennai | PHP Training Course
PHP Training in chennai | Online PHP Course
not working it is uploading last image only one image is going in database
ReplyDeleteim having issues with file size for uploads.. + connection being reset......... adjusting .htaccess just gives me a 500 internal server error... why do i get a huge long pause at the end of the upload? after 100% it just hangs for like 3-5minutes
ReplyDeleteSo how do i go ahead and insert the uploaded file name, size and url into a mysql database,
ReplyDeleteSo how do i go ahead and insert the uploaded file name, size and url into a mysql database,
ReplyDeleteIt would have been great if the script was accompanied with a tutorial on how to implement it, like here https://www.cloudways.com/blog/the-basics-of-file-upload-in-php/
ReplyDeleteGreat blog created by you. I read your blog, its best and useful information. You have done a great work. Super blogging and keep it up.
ReplyDeletephp jobs in hyderabad.
Good article, thanks for sharing.
ReplyDeletehotmail.com
• Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing your valuable information and time. Please keep updatingAzure Online course hyderabad
ReplyDelete