Upload Multiple Images Using PHP | Drag and Drop Image Upload

By | April 11, 2019
drag and drop multiple image upload

Uploading multiple images using php is the main thing  to achieve with this tutorial. In this article i will show you that how you can upload multiple images using Jquery Drag and Drop Feature. We will also save the uploaded values to the database so that you can use it further.

I have already written a tutorial regarding uploading images to database using PHP. If you want t upload one by one images you can use the previous tutorial.

For uploading the Multiple images we have 2 methods One is simple input file tag to upload the image other one is very easy and user friendly Drag and Drop Image upload. In this tutorial i will show you how you can use the Drag and Drop Method.




Thing’s We need.

  • Database
  • Jquery Plugin
  • HTML upload form
  • PHP Upload Class
  • List Images HTML Page
  • Connection Class

We will start with creating table in our database. In our database table  we will save only the name of the image file so we can use it our website dynamically.

CREATE TABLE webimages (
  WID int(11) NOT NULL,
  Text varchar(40) NOT NULL,
  Image varchar(150) NOT NULL,
  PRIMARY KEY (WID)
)

Above is the code for creating our table in our database which will hold the text and image. We need some text to show with the image so this text field will be used.

Now we will use the Drag and Drop Dropzone Jquery part. In this part we will add some jquery to create our drag and drop area workable. In this example you will see that we are uploading 5 images at a time.

<script src="dropzone/dist/dropzone.js" type="text/javascript"></script>
<script type="text/javascript">
  Dropzone.autoDiscover = false;
  var dropzone1 = new Dropzone('#imageDropzone', {
          maxFiles:5,
          forceFallbacks:true,
          autoDiscover:false,
          createImageThumbnails:false,
          init:function(){
              this.on("success",function (file,response){
                  alert(response);
              });
          }
     });
 </script>

index.php

Now we will create our form to upload the image. In form attribute action will be “getImage.php” and method will be post.

<form id="imageDropzone" action="getImage.php" enctype="multipart/form-data" class="dropzone">
  <div class="dz-message">
  <div class="icon"><span class="fa fa-cloud fa-3x"></span></div>
  <h3>Drag and Drop Images here</h3>
  </div>
</form>

After putting this code you will see that there is a drag and drop area in your page. Some more code related to the styling i have added the boostrap and fontawesome. You can download the whole working zip from bottom of the article.

getImage.php

In this page we will write the code for uploading the image to the folder and save the image to the database. For uploading the image first of all we will check the $_FILE if we found it empty then we will show the error else we will start uploading the image.

<?php
error_reporting(E_ALL & ~E_NOTICE & ~E_USER_NOTICE);
$storeFolder = 'gallery/';
if (!empty($_FILES)) {
    $tempFile = $_FILES['file']['tmp_name'];   
    $ran = time();
    $targetPath = $storeFolder;
    $fileName=$ran.$_FILES['file']['name'];
    $targetFile =  $targetPath.$fileName;
    move_uploaded_file($tempFile,$targetFile);
}
else
{
    echo "Image not found";
}
?>

In the above code you can see we have added a folder by the name of “gallery” where images will be uploaded. If you run the application till now then you can see that images are uploading in the folder successfully.

Now we will use the file name of uploaded image and save it to our database. Now we will just update the above code and it will send the filename and other values to the “imageClass.php”.

<?php
error_reporting(E_ALL & ~E_NOTICE & ~E_USER_NOTICE);
$storeFolder = 'gallery/';
if (!empty($_FILES)) {
    $tempFile = $_FILES['file']['tmp_name'];  
    $ran = time();
    $targetPath = $storeFolder;
    $fileName=$ran.$_FILES['file']['name'];
    $targetFile =  $targetPath.$fileName;
    move_uploaded_file($tempFile,$targetFile);
    $data["Image"]=$fileName;
include_once '/imageClass.php'; 
$imageClass=new imageClass();
    $alert=$imageClass->addImages($data);
}
else
{
    echo "Image not found";
}

As you can see we have added some more code to the above code. Now this code will get the image file name and save it to the database. we have added some more data also which will be used in enabling and positioning the data.

imageClass.php

In this class we will add our functions for adding the image to our database with status and position. You will find some more functions also which can be used for other things like – listing the images

<?php
require_once( dirname( __FILE__ ) . '/../functions/connectionClass.php' );

class imageClass extends connectionClass{
    
    public function addImages($data){
        $this->set_charset('utf8');
        $data["Image"]=$this->real_escape_string($data["Image"]);
        $keys=array_keys($data);
        $values=array_values($data);
        date_default_timezone_set ("Asia/Kolkata");
        $query='INSERT INTO webimages ('.implode(', ', $keys).') VALUES ("'.implode('","', $values).'")';
        $result=  $this->query($query) or die($this->error);
        if($result){
            return "1";
        }
        else
        {
            return "2";
        }
    }
    
    public function listImages($limit,$page,$query){
        $this->set_charset('utf8');
            if($limit=="" && $page==""){
            $list="select * from webimages $query";
        }
        else
        {
            if($page==""){$page=1;}
            $start=$page - 1;
            $perpage=$start * $limit;
            $list="select * from $table $query Limit $perpage,$limit";
        }
        date_default_timezone_set ("Asia/Kolkata");
        $result=  $this->query($list);
        $count=  $result->num_rows;
        if($count < 1){}else{
            while($row= $result->fetch_array(1)){
                $arr[]= $row;
            }
            return $arr;
        }
    }
}





Above code will list and add the  images.

Connection.php

This part is just for declaring the database connection and use it in the project.

<?php
class connectionClass extends mysqli{
    private $host="localhost",$dbname="imagedatabase",$dbpass="",$dbuser="root";
    public $con;
    
    public function __construct() {
        $this->con=  $this->connect($this->host, $this->dbuser, $this->dbpass, $this->dbname);
        if($this->con){}
        else{
//            echo "<h1>Error while connecting to database</h1>";
        }
    }
}

List.php

This file will show you the added images over the website.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" >
<link href="dropzone/dist/dropzone.css" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css">
<style>
    .imagebox img{border: 1px solid #c9c9c9;padding: 5px;margin-bottom: 10px;}
</style>

<?php
include_once './imageClass.php';
$imageClass=new imageClass();
$listImages=$imageClass->listImages("", "", "");
if(count($listImages)){
    foreach ($listImages as $value) {
        echo '<div class="col-md-3 imagebox">
    <img src="gallery/'.$value["Image"].'" width="100%">
</div>';
    }
}
?>

Hope you like the Upload Multiple Images Using PHP tutorial. if you have face any issue or have any questions then please comment below.

Draganddropimage
Draganddropimage
draganddropimage.zip
36.5 KiB
916 Downloads
Details...

5 thoughts on “Upload Multiple Images Using PHP | Drag and Drop Image Upload

  1. download

    Everything is very open with a very clear description of the issues.

    It was definitely informative. Your site is extremely helpful.
    Many thanks for sharing!

    Reply
  2. Caleb

    Thanks alot for this. Was wondering why it only works on local server. Keeps giving errors when i tried it on live server

    Reply
    1. Vivek Moyal Post author

      Debug and check that you have uploaded all the files in your server and they are connected properly to your page

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *