php upload files, php file upload, php upload multiple files,  upload file jQuery, upload image,

How to upload multiple files using PHP and JQuery

File upload is a key feature in website development since it focuses on using either graphics or files to support and elaborate on the topic that is being discussed

Mostly, file upload is used in eCommerce websites that focus on selling products using the internet whereby the item displayed or sold must be supported with an image

In a previous article, we discussed how you can upload images using PHP and jQuery where we highlighted the steps you need to follow so that you can store images to a server

In this article, we shall discuss how you can use PHP and jQuery to upload multiple files to a server.

  • First, you need to define a form that will have the input type which will be a file type, in our case our form uses bootstrap classes

While defining the form, you have to add the attributes

  • The method as POST, that is, method="POST"
  • Enctype attribute which will allow upload of files as enctype="multipart/form-data"
  • Form id which will identify the form during submission of the data

The form is defined as follows

<form method="post" id="upload_multiple" enctype="multipart/form-data">

</form>

  • Add input which will have attributes
  • Type as file to allow browsing inside the device documents
  • Required which will ensure that the input must have a value before submitting
  • Name of the input but in this case, for it to upload multiple values it must be defined as an array, for example, if the name of the input is images you will have to define [] next to the name as images[]
  • Also, you have to add attribute multiple which will ensure that multiple files are selected
  • Accept attribute to define the type of files you want to be selected if images use accept="image/*" to accept all image types, you can refine further if you want png or jpg only

The input will be as follows

<form method="post" id="upload_multiple" enctype="multipart/form-data">

<label>Select image</label>

<input type="file" class="form-control" name="images[]" accept="image/*" multiple required>

</form>

  • Add the submit button below the input and define the type as submit as follows

<button class="btn btn-primary" type="submit"> Upload Files</button>

The form with the input and the button will be as follows

<form method="post" id="upload_multiple" enctype="multipart/form-data">

<label>Select image</label>

<input type="file" class="form-control" name="images[]" accept="image/*" multiple required>

<button class="btn btn-primary" type="submit"> Upload Files</button>

</form>

Please note

When you run the code above and click choose files, to select multiple files if you are using windows;

Hold the CTRL button and then select as many files as you wish

Next, we need to submit or upload the files using jQuery using the steps below

  • Initiate jQuery  by adding the script shown before adding submit code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

  • Define the submit function provided by jQuery library which will be used together with ajax to collect form data to the server as shown below

<script>

    // submit function

$("#upload_multiple").submit(function(e){

    e.preventDefault();

     $.ajax({

// method used to send data for processing is POST

       method: "POST",

// location of the file that will process data

       url: "upload-files.php",

// the form data from the input

       data: new FormData(this),

       contentType: false,

       processData: false,

       cache:false

     }).done(function(data){

     if(data.status == "200"){

      alert(" files uploaded successfully ");

     } 

     if(data.status == "300"){

      alert(" an error encountered ");      }

     });

    });

    </script>

  • The full front end code for defining the form and sending data to the PHP file for processing using jQuery is as follows

<!DOCTYPE html>

<html>

<head>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

</head>

<body>

<form method="post" id="upload_multiple" enctype="multipart/form-data">

<label>Select image</label>

<input type="file" class="form-control" name="images[]" accept="image/*" multiple required>

<button class="btn btn-primary" type="submit"> Upload Files</button>

</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

    // submit function

$("#upload_multiple").submit(function(e){

    e.preventDefault();

     $.ajax({

// method used to send data for processing is POST

       method: "POST",

// location of the file that will process data

       url: "upload-files.php",

// the form data from the input

       data: new FormData(this),

       contentType: false,

       processData: false,

       cache:false

     }).done(function(data){

     if(data.status == "200"){

      alert(" files uploaded successfully ");

     } 

     if(data.status == "300"){

      alert(" an error encountered ");      }

     });

    });

    </script>

 

</body>

</html>

  • Next, you will need to define the PHP code that will process the data submitted

The code to submit files to the server and save file names in the database as an object is as follows

<?php

//database connection file (ensure the location defined is correct)

include_once('db_connect.php');

//the content type is json

header("Content-Type:application/json");

   

    //define images name and remove any spaces that may be between names or characters

     $images = str_replace(" ","",$_FILES['images']['name']);

    $file_tmp =$_FILES['otherimages']['tmp_name'];

    //count the number of images selected

     $file_count = count($images);

     //define an empty array

    $imgs=array();

    //upload each image as independent using for loop

    for($i = 0; $i < $file_count; $i++) {

    //filename for each separate uploaded file

    $filename = $otherimage[$i];

    $tmp = $file_tmp[$i];

 

    // move the file to the upload folder defined

      move_uploaded_file($tmp, "uploads/".$filename);

    //add each file or image to the empty array defined     

    array_push($imgs,$filename);

    }

   //encode the array

    $img=json_encode($imgs);

 

 //save the encoded array to the database

     if(mysqli_query($con,"INSERT INTO destinations(images) VALUES('$img')")){

       echo json_encode(array("status" => 200, "message" => "SUCCESS"));

      }

      else{

        echo json_encode(array('status' => 300,'message' => mysqli_error($con)));

      }

?>

Once that is done, the multiple files will be uploaded to the defined folder, and the names of each file stored in the database as a single JSON object

An example of how the JSON object for the multiple files is stored in the database is as follows

["file1.jpg","file2.jpg","file3.jpg","file4.jpg","file5.jpg"]

How to extract files from JSON object

To access the files stored as a json object and get the individual element, we use the code below

<?php

$json_object=["file1.jpg","file2.jpg","file3.jpg","file4.jpg","file5.jpg"];

// decode the json object

$decoded_object=json_decode($json_object);

// get the number of items in the array

 $number_of_items_in_array=count($decoded_object);

// use for loop to access each item

 for($item=0; $item<$number_of_items_in_array; $item++){

// display each item

echo $decoded_object [$item];

?>

 

Conclusion

In the above discussion, we have highlighted the major steps used while uploading multiple files using PHP and jQuery and also highlighted how you can extract each item from a JSON object

Hope you have followed the steps well. For any queries, reach to us through the channels provided. Happy coding