Multiple File Upload in Multiple Time Php Mysql Jquery
For the topic of Multiple File Upload, there are various approaches including HTML, jQuery AJAX, and PHP. This ultimate complete guide helps y'all understand how to choose a proper method among them. For example, only PHP gyre method is available for the case of file transfer betwixt hosts.
All codes hither are non complicated, and so y'all tin can easily understand even though you are still students in schoolhouse. To benefit your learning, we will provide you download link to a aught file thus you tin get all source codes for future usage.
Estimated reading time: 11 minutes
EXPLORE THIS ARTICLE
Table OF CONTENTS
BONUS
Source Code Download
We accept released information technology under the MIT license, so feel complimentary to utilise it in your ain project or your schoolhouse homework.
Download Guideline
- Fix HTTP server such equally XAMPP or WAMP in your windows environment.
- Download and unzip into a folder that http server can access.
DOWNLOAD SOURCE
Department 1
Html Multiple File Upload
Apart from our previous article for Single File Upload in PHP, by now, we will talk well-nigh multiple file upload. The nearly direct way to be discussed in the section is using HTML <grade>
element with a lot of <input>
tags that can hold file or data.
Method 1A – HTML FORM Upload (Files)
For multiple files upload to a PHP server, it is direct and simple to employ HTML <grade>
element in browser clients. Most chiefly, when making a POST request, you should encode the torso of information by specifying a way of enctype="multipart/form-data"
. It does protect all your data in <input type="file">
elements.
upload-1A.html
<!DOCTYPE html> <!-- method 1A - upload multiple files by HTML Form --> <html> <head><link rel="stylesheet" href="upload.css"></caput> <body> <form action="http://localhost/wpp/exams/a0011/server/multiple-upload.php" method="postal service" enctype="multipart/form-data"> <input type="file" name="myfile[]" multiple> <input type="submit" value="Upload"> </form> </body> </html>
With <input>
tag, the array definition of blazon="file" name="file[]" multiple
allows selecting more than one file in dialog box. When clicking on blazon="submit"
, the browser confirms to upload multiple files.
Method 1B – HTML FORM Upload (Files & Data)
Sometimes, developers require ship data forth with files at a time. A subconscious <input>
element with type="hidden"
will not only upload data, but also make data invisible. The data to exist sent could exist a simple string or JSON data, similar the example as below.
{method:'method ii', msg:'upload file forth with data by HTML Form'}
upload-1B.html
<!DOCTYPE html> <!-- method 1B - upload multiple files forth with data by HTML Grade --> <html> <head><link rel="stylesheet" href="upload.css"></head> <trunk> <grade action="http://localhost/wpp/exams/a0011/server/multiple-upload.php" method="mail service" enctype="multipart/form-information"> <input type="file" proper noun="myfile[]" multiple> <input type="hidden" name="data" value="{method:'method two', msg:'upload multiple files along with data past HTML Form'}"> <input type="submit" value="Upload"> </grade> </body> </html>
Section two
jQuery Ajax Multiple File Upload
The next method to be learned is jQuery AJAX. The jQuery call $.ajax()
can transfer multiple files from browser clients to a server site, which accepts file upload using PHP. Specially, the key betoken is the FormData object that can carry multiple files and data by means of Post method.
Method 2A – jQuery AJAX Upload (Files)
For HTML <class>
chemical element, user'south decision on information technology will trigger JQuery codes $("#form").submit()
to make an AJAX request. Before that request, the and so FormData object gathers multiple files from HTML <form>
element, where $("#form")[0]
is equal to the HTML <course>
element.
upload-2A.html
<!DOCTYPE html> <!-- method 2A - upload multiple files by jQuery --> <html> <caput> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <link rel="stylesheet" href="upload.css"> </caput> <body> <class id="grade"> <input type="file" name="myfile[]" multiple> <input type="submit" value="Upload"> </form> </body> </html> <script> $(document).ready(function() { $("#form").submit(function(east){ due east.preventDefault(); var formData = new FormData($("#course")[0]); $.ajax({ url : "http://localhost/wpp/exams/a0011/server/multiple-upload.php", type : "postal service", information : formData, contentType : faux, processData : false, success: function(resp) { console.log(resp); warning(resp); } }); }); }); </script>
Next, the AJAX call, $.ajax()
, uploads a multiple files inside data : formData
.
Method 2B – jQuery AJAX Upload (Files & Data)
Based on Method 2A, Method 2B volition upload information, along with multiple files, at a time. First, JSON.stringify(data)
converts Javascript object information={...}
to be a JSON annotation, and then formData.append()
append this JSON at end of formData
object with the key of 'data'
.
upload-2B.html
<!DOCTYPE html> <!-- method 2B - upload multiple files along with data past jQuery --> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.four.1/jquery.min.js"></script> <link rel="stylesheet" href="upload.css"> </head> <trunk> <class id="class"> <input blazon="file" proper name="myfile[]" multiple> <input blazon="submit" value="Upload"> </form> </torso> </html> <script> $(document).ready(function() { $("#form").submit(function(e){ east.preventDefault(); var formData = new FormData($("#form")[0]); data = {method: 'method 4', msg:'upload multiple files along with information past jQuery'}; for(key in data) { formData.append("data["+key+"]", data[cardinal]); } $.ajax({ url : "http://localhost/wpp/exams/a0011/server/multiple-upload.php", type : "post", data : formData, contentType : false, processData : false, success: function(resp) { console.log(resp); alarm(resp); } }); }); }); </script>
In other words, FormData object comprise both multiple files and information. Besides, $.ajax()
, uploads data : formData
to a PHP server finally.
Department 3
Php Multiple File Upload
All the 4 methods in previous sections permit browser clients to upload multiple files to hosts, while the next 2 methods using purely PHP scripts mainly transfer multiple files between hosts. Besides, there are different script writings for various PHP versions hither. Finally in the section, we will talk about a complex JSON compared with a simple string for file upload.
Method 3A – PHP Upload (Files)
The cURL is a basic PHP library that tin help you transfer files or data over HTTP or FTP. Moreover, information technology executes multiple file upload between hosts without aid of browsers. Allow us explain this method by a command line as below.
$ php upload-3A.php success: Assortment ( [0] => in_transit.png [1] => home.png [two] => customer_support.png )
Fundamentally, PHP roll uses iii functions of curl_init()
, curl_setopt()
, and curl_exec()
to achieve the goal. Chiefly, the parameter CURLOPT_POSTFIELDS
defines Postal service information to be sent, and the key 'myfile[]'
in array will outcome in the notation of $_FILES['myfile'][]
at server site.
Actually, this annotation is a little scrap complex. Thus it is suggested to refer to the side by side department Multiple File Upload Server, which volition show it clearly.
upload-3A.php
<?php /* method 3A - upload multiple files past pure PHP */ $url = "http://localhost/wpp/exams/a0011/server/multiple-upload.php"; $path = array("images/in_transit.png", "images/dwelling house.png", "images/customer_support.png"); $ary = array(); foreach ($path every bit $key=>$item) { if (function_exists('curl_file_create')) { // php 5.v+ $cFile = curl_file_create($particular); } else { // echo 'PHP ' . phpversion() . PHP_EOL; $cFile = '@' . realpath($particular); } $ary['myfile['.$key.']'] = $cFile; } $req = curl_init($url); curl_setopt($req, CURLOPT_HEADER, imitation); curl_setopt($req, CURLOPT_POST, true); curl_setopt($req, CURLOPT_POSTFIELDS, $ary); curl_setopt($req, CURLOPT_RETURNTRANSFER, true); curl_setopt($req, CURLOPT_TIMEOUT, x); $data = curl_exec($req); echo $data; ?>
The $cFile
is a CURLFile object. Yet, because curl_file_create()
only exists in versions of PHP v.5 above, other PHP versions create it by using realpath()
.
Finally, the $ary['myfile['.$key.']']
holds all CURLFile objects as an array to be included in the CURLOPT_POSTFIELDS
field.
Method 3B – PHP Upload (Files & Information)
If uploading data together with multiple files using PHP is required, the example Method 3B will prove yous. The data can be a unproblematic string or data array. Let united states see the deviation in notation between a simple string and data array.
The notation about data array is a little bit special, isn't it? The 'data[method]'
and 'data[msg]'
as the post-obit get together to be a data array, and then PHP cURL sends it by a POST request.
upload-3B.php
<?php /* method 3B - upload multiple files along with data past pure PHP */ $url = "http://localhost/wpp/exams/a0011/server/multiple-upload.php"; $path = assortment("images/in_transit.png", "images/domicile.png", "images/customer_support.png"); $ary = array(); foreach ($path as $key=>$item) { if (function_exists('curl_file_create')) { // php v.5+ $cFile = curl_file_create($item); } else { // echo 'PHP ' . phpversion() . PHP_EOL; $cFile = '@' . realpath($item); } $ary['myfile['.$key.']'] = $cFile; } $ary['data[method]'] = 'method six'; $ary['information[msg]'] = 'upload multiple files along with information by pure PHP'; $req = curl_init($url); curl_setopt($req, CURLOPT_HEADER, false); curl_setopt($req, CURLOPT_POST, true); curl_setopt($req, CURLOPT_POSTFIELDS, $ary); curl_setopt($req, CURLOPT_RETURNTRANSFER, truthful); curl_setopt($req, CURLOPT_TIMEOUT, 10); $data = curl_exec($req); echo $information; ?>
Department 4
Multiple File Upload Server
In the final section, let u.s.a. see how server sites handle multiple files upload using PHP. No thing in Windows or Linux, a temporary area is designed to go on incoming files, only they should exist moved out later. Besides, there are concerns in PHP setting nearly several file upload limits. At concluding, y'all will go tips for PHP cURL installation.
Movement Uploaded Files
Allow the states meet what data a PHP server site will get about file upload. The super global variable $_FILES["myfile"]
is a context of that. Amongst its backdrop, simply $_FILES["myfile"]["tmp_name"][0]~[ii]
will be mentioned hither.
Each item, such as ['tmp_name']
, in the $_FILES["myfile"]
here has 3 sub-items indexed by 0 to ii.
[myfile] => Array ( [name] => Array ( [0] => in_transit.png [i] => home.png [2] => customer_support.png ) [blazon] => Array ( [0] => application/octet-stream [1] => awarding/octet-stream [ii] => awarding/octet-stream ) [tmp_name] => Array ( [0] => C:\xampp\tmp\php106C.tmp [1] => C:\xampp\tmp\php107C.tmp [2] => C:\xampp\tmp\php107D.tmp ) [error] => Array ( [0] => 0 [1] => 0 [2] => 0 ) [size] => Array ( [0] => 8861 [i] => 5871 [2] => 4017 ) )
The PHP super global variable $_FILES["myfile"]["error"]
brings a set of error codes for multiple files. For each file, if the fault lawmaking is UPLOAD_ERR_OK, then information technology ways no fault. you lot can check sizes and move temporary files to your destination.
In improver, some other PHP super global variable chosen $_FILES["myfile"]["size"]
can help you limit size of each incoming file.
multiple-upload.php
<?php /* upload multiple files in one asking */ $upload_dir = 'uploads/'; $namelist = array(); foreach ($_FILES["myfile"]["mistake"] as $fundamental => $error) { if ($fault == UPLOAD_ERR_OK) { $name = basename($_FILES["myfile"]["name"][$key]); $target_file = "$upload_dir/$name"; if ($_FILES["myfile"]["size"][$fundamental] > 10000) { // limit size of 10KB echo "error: {$name} is too large. \northward"; go on; } if (!move_uploaded_file($_FILES["myfile"]["tmp_name"][$primal], $target_file)) echo 'fault:'.$_FILES["myfile"]["fault"][$key].' come across /var/log/apache2/error.log for permission reason'; else $namelist[] = $name; } } if (isset($_POST['information'])) print_r($_POST['data']); repeat "\north success: \n"; print_r($namelist); ?>
When multiple files arrive, PHP puts it in temporary area. The PHP server-site take to move them to destination by calling move_uploaded_file()
iteratedly. If exceptions occur during moving, the error reasons will announced in /var/log/apache2/error.log for Linux and in somewhere for Windows.
Usually, errors are prompted as permission denied when HTTP service is non available to create new files in target directory. At this time, y'all can grant permission to HTTP service by commmand lines every bit below, and and then try to upload once more. The www-data represents Apache2 user id on Ubuntu Linux.
$ chgrp www-data ~/uploads $ chmod g+w ~/uploads
PHP.INI
PHP configuration file locates in c:\xampp\php\php.ini for Windows and /etc/php/five.6/apache2/php.ini for PHP 5.6 in Ubuntu Linux, respectively.
The settings in PHP configuration file php.ini for file upload primarily define temporary directory, maximum immune file size, and maximum number of files.
;;;;;;;;;;;;;;;; ; Multiple File Uploads ; ;;;;;;;;;;;;;;;; ; Whether to let HTTP file uploads. ; http://php.net/file-uploads file_uploads=On ; Temporary directory for HTTP uploaded files (will use system default if not ; specified). ; http://php.net/upload-tmp-dir upload_tmp_dir="C:\xampp\tmp" ; Maximum allowed size for uploaded files. ; http://php.internet/upload-max-filesize upload_max_filesize=2M ; Maximum number of files that can be uploaded via a unmarried asking max_file_uploads=20
In Windows, Uncommenting the following setting in in c:\xampp\php\php.ini will enable PHP cURL.
extension=php_curl.dll
In Linux, PHP cURL tin can be installed using command lines for PHP 5.6.
$ sudo apt-get install php5.half-dozen-roll
And for PHP 7.2, utilise the following.
$ sudo apt-become install php7.2-scroll
Suggested Reading
- 6 Methods for File Upload in PHP, HTML, AJAX, jQuery
- 4 Practices for Python File Upload to PHP Server
- Loop Multidimensional Array in PHP past 3 Recursive Demos
Source: https://easycodeshare.com/multiple-file-upload-in-php-html-jquery-by-6-ways/