Multiple image upload and resize using AJAX and PHP

Manas Singh 28th Sep 2020

One of the most important features in the social media platforms is uploading and resizing multiple images using ajax without refreshing the web page. If you manage a website that serves a lot of users' data, you need to decrease the transferred data from your server to the browser as possible as you can.

So, page open speed will be higher and users' requests don't make use of huge bandwidth. Image resizing is one of the solutions to make your page only loads the needed data with more speed and less bandwidth.

We just need users' profiles photos in small in almost pages the exception is only their profile's page. So, it is so bad to view these small photos using a big size image. You just need to resize it while uploading it.

In this tutorial, you will learn how to upload images using jquery and PHP without refreshing pages and how to use PHP image functions for resizing images in different dimensions.

We need:

  • HTML form in index.php.
  • Use jquery.form.js to send ajax request.
  • Write PHP code for uploading images.
  • Write PHP code for resizing images.

Step1: In index.php we will create our HTML form that has file upload

<div id="viewall" style="width:888px">
<form enctype="multipart/form-data" name='upload-form' role="form" id="upload-form" method="post" action="ajax.php">
<div class="form-group">
<p>Please Choose Image: </p>
<input class='file' multiple type="file" class="form-control" name="photofile" id="photofile" placeholder="Upload your image">
<span class="help-block"></span>
</div>

</form>
</div>

div with id 'view all' will b used to include uploaded images
We will include jquery.js and jquery.form.js files inside the header and write the javascript code for sending the form data when the file upload input changes.

<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/jquery.form.js"></script>

<script type="text/javascript" >
$(document).ready(function() {
// an integer variable used to add unique number to evry image uploaded after loading the page
var int = 1;
// bind change event with the function responsible for ajax request
$('#photofile').on('change', function() {

$('#viewall').append('</p>
<div class="view" id ="img'+int+'" ></div>
<p>');
// add an image for loading to the new div
$('#img'+int).html('<img src="loader.gif" alt="Uploading...."/>');
// add a button responsible for deleting image
$('#viewall').append('<button class="delete">delete </button>');
// use ajaxForm object to send the form data without refreshing the page

$("#upload-form").ajaxForm({
// target key determines where to output the data returned after the request success
target: '#img'+int
}).submit();
// when the user click on delete button
$('.delete').click(function(){
// using selectors to get the source of the uploaded image using jquery selectors
var delete_btn = $(this);
var img_src = $(this).prev('.view').children('img').attr('src');
var img_id = $(this).prev('.view').attr('id');
$.ajax({
// ajax url to the php page that delete images
url:'ajax.php?do=delete',
data:{'image_file':img_src},
success: function(data){

if(data.match(/wrong_path/)){
alert('Problem in deleting image');
}else if(data.match(/delete_success/)){
// after the deletion success we erase the page from webpage using jquery selectors
//$('.delete').prev('.view').remove();
$('#'+img_id).remove();
delete_btn.remove();
alert('image was deleted sucessfully');
}
//else if(data.match(/delete_fail/)){
// alert('Problem in deleting image');
//}

}
});

})
int ++;
});
});
</script>

The bound the change event of the file input to the upload process. start by adding new elements to the page by appending them to #viewall div. These elements view a loader image and represent a delete button. Then, create an ajax object to send the form data using ajax request and made the target of the returned data  #img  element.

The second task was to add jquery and ajax deleting code to the click event of the '.delete' element.

Step2: PHP code for uploading images

Create 'uploads' folder, and inside it, create two folders:
- 'img' for the uploaded images

- 'thumbs' for the resized images

Create the ' ajax.php' that is responsible for uploading, resizing, and deleting images.

// check if there is avalid post request
if(isset($_POST) &amp;&amp; isset($_FILES['photofile']))
{
// uploading path
$upload_path = "uploads/img/";
// the valid image extensions that the script inly allow uploading it
$supported_formats = array("jpg", "png", "gif", "bmp");
// Get the name and the size of the image
$file_name = $_FILES['photofile']['name'];
$file_size = $_FILES['photofile']['size'];

if(strlen($file_name))
{
// extracting the extension from image file name
list($txt, $ext) = explode(".", $file_name);
if(in_array($ext,$supported_formats))
{
// restrict the image size option only this or less sizes are allowed
if($file_size&lt;(1024*1024))
{
// generate a uinique new name for the image
$actual_file_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$new_file_path = $upload_path.$actual_file_name;
// image place in the temporary folders in server
$tmp = $_FILES['photofile']['tmp_name'];
// upload the image using move_uploaded_file() function
if(move_uploaded_file($tmp, $new_file_path))
{
// after uploading start resising using my function resizeimg();
resizeimg($new_file_path, 'uploads/thumbs/'.$actual_file_name, 100, 100);

// out put an image element views the uploaded image
// this element will be returned by the ajax request to the index.php page
echo "<img class="img" src="&quot;.$new_file_path.&quot;" />";
}
else
echo "failed";
}
else{
echo "file cannot be more than 1 MB";
}
}
else{
echo "Unsupported file format we allow :jpg, png, gif, and bmp .";
}
}

else
echo "You didn't select any images";

exit;
}

Step3: PHP code for resizing images

We write resizing() function that resizes our images to thumbnails. It takes four parameters:

- $file: the original image file.

- $newfile: the path and the name for the new thumbnail.

- $newwidth: the width of the new thumbnail.

- $newheight: the height of the new thumbnail.

function resizeimg($file, $newfile, $newwidth, $newheight){
if(!is_file($file) == true){
echo 'Cannot find file, upload it again !';
exit();
}

list($width, $height) = getimagesize($file);
// prepare for creating a new image that would be the thumbnail image
$thumb = imagecreatetruecolor($newwidth, $newheight);
$pathinfo = pathinfo($file);

switch(strtolower($pathinfo['extension'])){
case "jpeg" || "jpg":
$source = imagecreatefromjpeg($file);
imagecopyresized($thumb, $source, 0, 0, 0, 0, floor($newwidth), floor($newheight), $width, $height);
imagejpeg($thumb, $newfile);
break;

case "png":
$source = imagecreatefrompng($file);
imagecopyresized($thumb, $source, 0, 0, 0, 0, floor($newwidth), floor($newheight), $width, $height);
imagepng($thumb, $newfile);
break;

case "gif":
$source = imagecreatefromgif($file);
imagecopyresized($thumb, $source, 0, 0, 0, 0, floor($newwidth), floor($newheight), $width, $height);
imagegif($thumb, $newfile);
break;

default:
$newfile = 'false';
break;
}
imagedestroy($thumb);
return $newfile;
}
?&gt;

Step4: PHP code for deleting images

In the 'ajax.php' file, write the code of deleting images and thumbnails. This will just unlink the image from the files.

// check if there is a GET request with correct value
if(isset($_GET['do']) &amp;&amp; $_GET['do']== 'delete'){
// images path
$image = $_GET['image_file'];
// thumbnails path
$thumb = str_replace('img','thumbs',$image);
if(!is_file($image) == true){
echo 'wrong_path';
exit();
}
// deleting the image and thumbnails files
$deleted1 = unlink($image);
$deleted2 = unlink($thumb);
if($deleted1 &amp;&amp; $deleted2){
echo 'delete_success';
}else{
echo 'delete_fail';
}

}

'ajax.php' file will be like this :

<?php

// check if there is avalid post request
if(isset($_POST) &amp;&amp; isset($_FILES['photofile']))
{
// uploading path
$upload_path = "uploads/img/";
// the valid image extensions that the script inly allow uploading it
$supported_formats = array("jpg", "png", "gif", "bmp");
// Get the name and the size of the image
$file_name = $_FILES['photofile']['name'];
$file_size = $_FILES['photofile']['size'];

if(strlen($file_name))
{
// extracting the extension from image file name
list($txt, $ext) = explode(".", $file_name);
if(in_array($ext,$supported_formats))
{
// restrict the image size option only this or less sizes are allowed
if($file_size&lt;(1024*1024))
{
// generate a uinique new name for the image
$actual_file_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$new_file_path = $upload_path.$actual_file_name;
// image place in the temporary folders in server
$tmp = $_FILES['photofile']['tmp_name'];
// upload the image using move_uploaded_file() function
if(move_uploaded_file($tmp, $new_file_path))
{
// after uploading start resising using my function resizeimg();
resizeimg($new_file_path, 'uploads/thumbs/'.$actual_file_name, 100, 100);

// out put an image element views the uploaded image
// this element will be returned by the ajax request to the index.php page
echo "<img class="img" src="&quot;.$new_file_path.&quot;" />";
}
else
echo "failed";
}
else{
echo "file cannot be more than 1 MB";
}
}
else{
echo "Unsupported file format we allow :jpg, png, gif, and bmp .";
}
}

else
echo "You didn't select any images";

exit;
}

// check if there is a GET request with correct value
if(isset($_GET['do']) &amp;&amp; $_GET['do']== 'delete'){
// images path
$image = $_GET['image_file'];
// thumbnails path
$thumb = str_replace('img','thumbs',$image);
if(!is_file($image) == true){
echo 'wrong_path';
exit();
}
// deleting the image and thumbnails files
$deleted1 = unlink($image);
$deleted2 = unlink($thumb);
if($deleted1 &amp;&amp; $deleted2){
echo 'delete_success';
}else{
echo 'delete_fail';
}

}

function resizeimg($file, $newfile, $newwidth, $newheight){
if(!is_file($file) == true){
echo 'Cannot find file, upload it again !';
exit();
}

list($width, $height) = getimagesize($file);
// prepare for creating a new image that would be the thumbnail image
$thumb = imagecreatetruecolor($newwidth, $newheight);
$pathinfo = pathinfo($file);

switch(strtolower($pathinfo['extension'])){
case "jpeg" || "jpg":
$source = imagecreatefromjpeg($file);
imagecopyresized($thumb, $source, 0, 0, 0, 0, floor($newwidth), floor($newheight), $width, $height);
imagejpeg($thumb, $newfile);
break;

case "png":
$source = imagecreatefrompng($file);
imagecopyresized($thumb, $source, 0, 0, 0, 0, floor($newwidth), floor($newheight), $width, $height);
imagepng($thumb, $newfile);
break;

case "gif":
$source = imagecreatefromgif($file);
imagecopyresized($thumb, $source, 0, 0, 0, 0, floor($newwidth), floor($newheight), $width, $height);
imagegif($thumb, $newfile);
break;

default:
$newfile = 'false';
break;
}
imagedestroy($thumb);
return $newfile;
}
?>

At the end of this article, you knew how to upload images in PHP and using ajax and how to resize it.

Authored By Manas Singh

He is a continuous blogger and has blogged on different topic. He loves to surf Internet and always trying to get new Idea about new Technology and Innovations and sharing these great information to all the technology lovers.

Also on DiscussDesk