If you want to upload multiple files in PHP then you will require to read the files in the form of an array. It will push file one by one from the source path to the destination path using the loop. But in this case, you cannot achieve the simplicity of the file upload. You will have to choose the multiple files by clicking on the browse file. So to achieve the drag and drop file uploading in PHP, I am going to use the jQuery file upload. I have already shown you the PHP file upload using jQuery and Ajax. It was a simple way to upload a single file without refreshing the form. Here, I’ll be showing you the multiple file upload in PHP using dropzone.
jQuery File Upload
The jQuery provides the library for drag and drop file upload which is dropzone. This is the open-source library which previews the images after the upload. So, I will integrate the dropzone js library for uploading the multiple files as drag and drop in the PHP.
Also, I will store the uploaded file name into the database. So let’s create a project first.
jQuery File Upload Using Dropzone Js
- In the initial step, you will have to download the Dropzone Js library from the official website.
- Also, you can download the complete files like JS and CSS from the Github.
- Once you downloaded the files, just paste the files into your project directory.
- Now, create the index.php file and paste the below code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Dropzone Multiple File Upload in PHP</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<!--------- Dropzone JS and CSS file --------->
<script src="./dropzone.js"></script>
<link rel="stylesheet" href="./dropzone.css">
<!----------- Custom CSS ------->
<style>
body{
background-color: #054b4ebd;
}
.dropzone {
border: 2px dashed rgb(65, 65, 149);
max-height: 400px;
padding: 0px 20px !important;
}
span {
font-size: 25px;
}
#icon {
max-width: 150px;
}
</style>
</head>
<body>
<div class="container pt-5">
<div class="row">
<div class="col-md-8 m-auto">
<form action="./upload.php" class="dropzone"></form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<!----------- Custom JS --------------->
<script>
$(document).ready(function() {
$("span").html("<h3>Drop files here <br/> Or </h3> <small> Click to Upload</small>");
$("span").css('text-align', 'center');
$("<div><img src='./upload-icon.png' class='img-rounded' id='icon'></div>").insertAfter("span");
});
</script>
</body>
</html>
- In the above code, I have integrated the Bootstrap CDN (not necessary).
- Then, I have linked the dropzone JS and CSS file which has downloaded.
- Created a form with action. In the action, I have passed a PHP page URL in which, I will move the file from source to destination. Also, I will be storing the file name into the database.
- Save and execute the above script to see the result as below.
Dependent Dropdown Filter in PHP Using jQuery and Ajax
Upload Files in PHP
- In the next step, create a folder in the project directory in which the files will be uploaded. (In my case, the folder name is uploads.
- Here the form action is upload.php. So, create a new file named upload.php and paste the following code.
<?php
// ------------- Check if file is not empty ------------
if(!empty($_FILES)) {
$fileName = $_FILES['file']['name'];
$source_path = $_FILES['file']['tmp_name'];
$fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
// ------ Replacing file name with new file name ---------
$targetFile = time()."-".time()."-".strtolower(str_replace(" ","-",$fileName));
$target_path = "./uploads/".$targetFile;
if(move_uploaded_file($source_path, $target_path)) {
echo "File uploaded successfully";
}
}
?>
- In the above code, I have read the files from the dropzone js which is sent from the index.php file.
- Then got the file extension of the uploaded file.
- For suitability of the filename, I have replaced the old file name into a new one by replacing the current date-time using the time() function.
- In the next step, I have moved the file from source path to the destination path which is in the uploads folder with the new file name.
- Here, is the preview of the result.
Import CSV File Data into MySQL Database Using PHP
- You can see in the uploads folder, the files are uploaded.
Now, I will store the uploaded files into the database table too. So let’s move to the database operations.
Ajax PHP Form Handling Using jQuery
Save Files into the Database
- Create a new database in phpMyAdmin section.
- Then, create a table inside the database.
- Here are the database and the table structure.
-- phpMyAdmin SQL Dump
-- version 4.8.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Aug 31, 2019 at 09:40 PM
-- Server version: 10.1.34-MariaDB
-- PHP Version: 7.2.7
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `jquery_file_upload`
--
-- --------------------------------------------------------
--
-- Table structure for table `img_upload`
--
CREATE TABLE `img_upload` (
`id` int(11) NOT NULL,
`img` varchar(100) NOT NULL,
`updated_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `img_upload`
--
ALTER TABLE `img_upload`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `img_upload`
--
ALTER TABLE `img_upload`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Load MySQL Data in PHP Using jQuery and Ajax
Create Database Connection
In the project directory, create a new file named config.php and paste the below code.
<?php
// ----------------- Database connection ----------------
$hostname = "localhost";
$username = "root";
$password = "root";
$dbname = "jquery_file_upload";
$conn = mysqli_connect($hostname, $username, $password, $dbname) or die("Db connect error" .mysqli_connect_error());
?>
Please replace your database credentials like username, password and the database name.
- Now, include the db-config.php file in the upload.php file so that it can store the filename into the selected database table.
- So, navigate to the upload.php file and add this single line of code at the top of the file.
include_once "./db-config.php";
Save Filename into the database
In the next step, add the below code after the move_uploaded_file() function.
$sql = "INSERT INTO img_upload (img) VALUES ('".$targetFile."')";
$result = mysqli_query($conn, $sql);
if($result) {
echo "File uploaded successfully";
}
So, now the source code of upload.php will be this.
<?php
include_once "./db-config.php";
// ------------- Check if file is not empty ------------
if(!empty($_FILES)) {
$fileName = $_FILES['file']['name'];
$source_path = $_FILES['file']['tmp_name'];
$fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
// ------ Replacing file name with new file name ---------
$targetFile = time()."-".time()."-".strtolower(str_replace(" ","-",$fileName));
$target_path = "./uploads/".$targetFile;
if(move_uploaded_file($source_path, $target_path)) {
// --------- Inserting into the table ------------
$sql = "INSERT INTO img_upload (img) VALUES ('".$targetFile."')";
$result = mysqli_query($conn, $sql);
if($result) {
echo "File uploaded successfully";
}
else {
echo "Some error encountered. Please try again.";
}
}
}
?>
- To check whether the file is uploading properly run the project.
- Drag and drop the multiple files and see the result as a preview.
- Open the database and check the tables. Here, you can see that the file names are stored in the database table.
Conclusion
In the resultant, you can see that we have done drag and drop file upload in the jQuery file upload approach for PHP. We used the dropzone js library which is open-source. You can design and use it as per your requirements. This is a simple demo to show you how you can implement the drag and drop features for jQuery file upload in the PHP. I hope, it will help you. Please let me know if you face any problem regarding this post. I will help you in the comment section.
Bunty Verma says
It’s very helpful for me thank you so much.