The most commonly utilised feature of the online application is file or image upload. When you wish to allow a user to upload a file to your server, the file upload functionality is useful. Using PHP and HTML file input fields, you may easily upload a file. In most circumstances, the online application only permits one file to be uploaded at a time. However, if you want the user to be able to submit several files, uploading them all at once will give a wonderful user interface.
You can upload many photos at once using PHP. However, you may give a user-friendly interface that allows users to submit many photographs with a single click without having to refresh the page. Using jQuery and Ajax, the photos may be uploaded without reloading the page. Using jQuery Ajax and PHP, we’ll show you how to upload many images without refreshing the page in this article. Using jQuery and PHP, the example code demonstrates the Ajax multiple picture upload procedure.
Uploading Files Form (index.html)
This file is responsible for selecting numerous pictures and sending Ajax requests.
Create an HTML form with a file input box so that the user can choose numerous files.
The method=”post” and enctype=”multipart/form-data” attributes must be present in the form> tag.
The type=”file” property and multiple attributes must be included in the input> tag.
<div class="upload-div">
<!-- File upload form -->
<form id="uploadForm" enctype="multipart/form-data">
<label>Choose Images</label>
<input type="file" name="images[]" id="fileInput" multiple >
<input type="submit" name="submit" value="UPLOAD"/>
</form>
<!-- Display upload status -->
<div id="uploadStatus"></div>
</div>
Define a DIV element on the web page that will be used to display the submitted photographs in a gallery view.
<!-- Gallery view of uploaded images -->
<div class="gallery"></div>
The jQuery and Ajax libraries will be needed to upload files, so include the jQuery library first.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The following jQuery code uses Ajax to transfer the data from the selected photos to the server-side script.
The data from the selected files is communicated to the server-side script (upload.php) using jQuery and Ajax when the form is submitted.
The uploaded picture data is retrieved using the FormData object.
The upload status is displayed to the user based on the response, and the uploaded images are appended to the specified element.
The MIME type of the selected files will also be verified, limiting the user to just uploading images.
<script>
$(document).ready(function(){
// File upload via Ajax
$("#uploadForm").on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'upload.php',
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend: function(){
$('#uploadStatus').html('<img src="images/uploading.gif"/>');
},
error:function(){
$('#uploadStatus').html('<span style="color:#EA4335;">Images upload failed, please try again.<span>');
},
success: function(data){
$('#uploadForm')[0].reset();
$('#uploadStatus').html('<span style="color:#28A74B;">Images uploaded successfully.<span>');
$('.gallery').html(data);
}
});
});
// File type validation
$("#fileInput").change(function(){
var fileLength = this.files.length;
var match= ["image/jpeg","image/png","image/jpg","image/gif"];
var i;
for(i = 0; i < fileLength; i++){
var file = this.files[i];
var imagefile = file.type;
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]) || (imagefile==match[3]))){
alert('Please select a valid image file (JPEG/JPG/PNG/GIF).');
$("#fileInput").val('');
return false;
}
}
});
});
</script>
Using PHP to Upload Multiple Images (upload.php)
The Ajax request calls the upload.php file, which uses PHP to perform the image upload process.
Using the PHP $_FILES function, get the pictures data from the uploaded data.
Using PHP’s move uploaded file() method, post the photos to the server.
Create an HTML view using the photographs you’ve uploaded.
<?php
if(!empty($_FILES['images'])){
// File upload configuration
$targetDir = "uploads/";
$allowTypes = array('jpg','png','jpeg','gif');
$images_arr = array();
foreach($_FILES['images']['name'] as $key=>$val){
$image_name = $_FILES['images']['name'][$key];
$tmp_name = $_FILES['images']['tmp_name'][$key];
$size = $_FILES['images']['size'][$key];
$type = $_FILES['images']['type'][$key];
$error = $_FILES['images']['error'][$key];
// File upload path
$fileName = basename($_FILES['images']['name'][$key]);
$targetFilePath = $targetDir . $fileName;
// Check whether file type is valid
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(in_array($fileType, $allowTypes)){
// Store images on the server
if(move_uploaded_file($_FILES['images']['tmp_name'][$key],$targetFilePath)){
$images_arr[] = $targetFilePath;
}
}
}
// Generate gallery view of the images
if(!empty($images_arr)){ ?>
<ul>
<?php foreach($images_arr as $image_src){ ?>
<li><img src="<?php echo $image_src; ?>" alt=""></li>
<?php } ?>
</ul>
<?php }
}
?>
Using PHP, you may provide a preview of the selected photographs without having to submit them to the server.
$images_arr = array();
foreach($_FILES['images']['name'] as $key=>$val){
$image_name = $_FILES['images']['name'][$key];
$tmp_name = $_FILES['images']['tmp_name'][$key];
$size = $_FILES['images']['size'][$key];
$type = $_FILES['images']['type'][$key];
$error = $_FILES['images']['error'][$key];
// File upload path
$fileName = basename($_FILES['images']['name'][$key]);
$targetFilePath = $targetDir . $fileName;
// Check whether file type is valid
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(in_array($fileType, $allowTypes)){
// Display images without storing in the server
$img_info = getimagesize($_FILES['images']['tmp_name'][$key]);
$images_arr[] = "data:".$img_info["mime"].";base64,".base64_encode(file_get_contents($_FILES['images']['tmp_name'][$key]));
}
}
Note :
We’ve shown you how to use Ajax and PHP to upload numerous photos. You can simply upload numerous files/images without using a jQuery plugin by using our sample script. The Ajax multiple file upload functionality is quite beneficial when you want to allow the user to upload several images. You may utilise Drag and drop file upload with Dropzone JS and PHP to make multiple picture upload more user-friendly.
I simply wished to appreciate you once again. I do not know what I might have undertaken without the type of secrets documented by you directly on my question. It was before a real frightening dilemma in my circumstances, however , coming across your skilled mode you dealt with the issue took me to weep over fulfillment. I am just happy for your help and even have high hopes you are aware of a powerful job you happen to be providing training most people through your website. More than likely you have never come across any of us.
PLEASE F0RWARD THiS EMAiL To SoMEoNE iN YoUR C0MPANY WH0 iS ALL0WED T0 MAKE IMPORTANT DECiSioNS!
We have hacked y0ur website https://phpcodeinformation.com and extracted y0ur databases.
How did this happen?
our team has f0und a vulnerability within y0ur site that we were able t0 exploit. After finding the vulnerability we were able t0 get your database credentials and extract your entire database and m0ve the inf0rmation to an offsh0re server.
What does this mean?
We will systematically go thr0ugh a series of steps 0f t0tally damaging y0ur reputati0n. First y0ur database will be leaked 0r s0ld to the highest bidder which they will use with whatever their intenti0ns are. Next if there are e-mails found they will be e-mailed that their informati0n has been s0ld 0r leaked and your site https://phpcodeinformation.com was at fault thusly damaging your reputation and having angry customers/ass0ciates with whatever angry customers/associates d0. Lastly any links that y0u have indexed in the search engines will be de-indexed based off 0f blackhat techniques that we used in the past t0 de-index our targets.
H0w d0 i stop this?
We are willing to refrain from destroying your site’s reputati0n f0r a small fee. The current fee is $3000 in bitcoins (.16 BTC).
Please send the bitcoin t0 the foll0wing Bitcoin address (Make sure to copy and paste):
33mwR4NYVGnvkivg3X9sy4znL4Rc7wNFhh
0nce y0u have paid we will automatically get informed that it was y0ur payment. Please note that you have to make payment within 5 days after receiving this e-mail 0r the database leak, e-mails dispatched, and de-index of your site WiLL start!
How do i get Bitcoins?
Y0u can easily buy bitcoins via several websites or even 0ffline fr0m a Bitcoin-ATM.
What if i d0n’t pay?
if y0u decide not t0 pay, we will start the attack at the indicated date and uph0ld it until y0u do, there’s n0 counter measure to this, you will 0nly end up wasting m0re m0ney trying to find a s0luti0n. We will completely destr0y y0ur reputation am0ngst g00gle and y0ur cust0mers.
This is n0t a h0ax, d0 n0t reply t0 this email, d0n’t try to reas0n 0r negotiate, we will not read any replies. once you have paid we will st0p what we were d0ing and you will never hear fr0m us again!
Please n0te that Bitcoin is anonym0us and n0 0ne will find 0ut that you have complied.