Please support us by disabling ad blocker for ...

Ajax Multiple Image Upload With Resize Using jQuery PHP

Posted by & filed under Ajax, HTML5, JQUERY, MYSQL, PHP.

In previous tutorial I had explained ajax single image upload using jQuery and PHP.

Ajax Image Upload Using jQuery, PHP and MySQL

In this tutorial we are going to see Ajax Multiple Image Upload With Resize Using jQuery PHP and  MySQL. To enable a user let select multiple image using single file input element you need to create a HTML file input element with the following properties.

<input multiple="multiple" type="file" name="images[]" id="images">


multiple=”multiple”  :  this attribute of the input file element, let the user to select multiple images.

name=”images[]” : here naming  the input file element in array format keeps all selected images property in array format. So that you easily handle images upload on the server side.



Ajax Multiple Image Upload With Resize Using jQuery PHP

Ajax Multiple Image Upload With Resize Using jQuery PHP

Step 1:

Create index.php file with HTML form and file input element with needed attributes to let user to select multiple images. Here is the HMTL file source.

<?php require_once 'config.php';?>
<!DOCTYPE html> 
	<title>Ajax Multiple Image Upload With Resize Using jQuery PHP</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link href='' rel='stylesheet' type='text/css'>
	<link rel="stylesheet" href="css/style.css" >	
	<div class="container">
		<h1 class="page-title" >Ajax Multiple Image Upload With Resize Using jQuery PHP</h1>
		<div class="form-container">
			<form enctype="multipart/form-data" name='imageform' role="form" id="imageform" method="post" action="ajax.php">
				<div class="form-group">
					<p>Please Choose Image: </p>
					<input class='file' multiple="multiple" type="file" class="form-control" name="images[]" id="images" placeholder="Please choose your image">
					<span class="help-block"></span>
				<div id="loader" style="display: none;">
					Please wait image uploading to server....
				<input type="submit" value="Upload" name="image_upload" id="image_upload" class="btn"/>
		<div class="clearfix"></div>
		<div id="uploaded_images" class="uploaded-images">
			<div id="error_div">
			<div id="success_div">
	<input type="hidden" id='base_path' value="<?php echo BASE_PATH; ?>">
	<script src="js/jquery.min.js"></script>
	<script type="text/javascript" src="js/jquery.form.min.js"></script>
    <script src="js/script.js"></script>




Now add folloowing two jquery libraries, these two are responsible for ajax multiple image upload.

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

Create script.js where we are going to keep our jQuery scripts.

<script src="js/script.js"></script>

Step 3:

Here is the script.js full jQuery script. This script.js is responsible for following operations

1. Do the validation before HMTL Form is submitted via ajax to the server, and asks to user to select valid images to upload.

2. Once the validations are success, it will post the HMTL Form via Ajax to the server.

3. At end of ajax image upload, it gets the response from the server and shows success or errors based the response from the server.

(function() {
		beforeSubmit: function() {	
			count = 0;
			val = $.trim( $('#images').val() );

			if( val == '' ){
				count= 1;
				$( "#images" ).next('span').html( "Please select your images" );

			if(count == 0){
				for (var i = 0; i < $('#images').get(0).files.length; ++i) {
			    	img = $('#images').get(0).files[i].name;
			    	var extension = img.split('.').pop().toUpperCase();
			    	if(extension!="PNG" && extension!="JPG" && extension!="GIF" && extension!="JPEG"){
			    		count= count+ 1
				if( count> 0) $( "#images" ).next('span').html( "Please select valid images" );

		    if( count> 0){
		    	return false;
		    } else {
		    	$( "#images" ).next('span').html( "" );


	    success: function(msg) {
		complete: function(xhr) {

			result = xhr.responseText;
			result = $.parseJSON(result);
			base_path = $('#base_path').val();
			$.each(result, function(index, value){
				if( value.success ){
					name = base_path+'images/'+value.success;
					html = '';
					html+= '<image src="'+name+'">';
					$('#uploaded_images #success_div').append( html );
				} else if( value.error ){
					error = value.error
					html = '';
					$('#uploaded_images #error_div').append( html );





Here comes PHP part, once HTML Form is posted using ajax to the server. PHP script get the all image properties (name, size and etc.) in array format. where this array is not proper format to handle, so we  need to restructured it.

function restructure_array(array $images)
	$result = array();

	foreach ($images as $key => $value) {
		foreach ($value as $k => $val) {
			for ($i = 0; $i < count($val); $i++) {
				$result[$i][$k] = $val[$i];

	return $result;

Following PHP script which generates thumbnail while uploading image to the server. Mostly these script will helpful to generate thumbnail for the user who is going to set profile pic as larger one, where you need to resize that larger image and set it as their profile pic. Here is the script.

function thumbnail($src, $dist, $dis_width = 100 ){

	$img = '';
	$extension = strtolower(strrchr($src, '.'));
		case '.jpg':
		case '.jpeg':
			$img = @imagecreatefromjpeg($src);
		case '.gif':
			$img = @imagecreatefromgif($src);
		case '.png':
			$img = @imagecreatefrompng($src);
	$width = imagesx($img);
	$height = imagesy($img);

	$dis_height = $dis_width * ($height / $width);

	$new_image = imagecreatetruecolor($dis_width, $dis_height);
	imagecopyresampled($new_image, $img, 0, 0, 0, 0, $dis_width, $dis_height, $width, $height);

	$imageQuality = 100;

		case '.jpg':
		case '.jpeg':
			if (imagetypes() & IMG_JPG) {
				imagejpeg($new_image, $dist, $imageQuality);

		case '.gif':
			if (imagetypes() & IMG_GIF) {
				imagegif($new_image, $dist);

		case '.png':
			$scaleQuality = round(($imageQuality/100) * 9);
			$invertScaleQuality = 9 - $scaleQuality;

			if (imagetypes() & IMG_PNG) {
				imagepng($new_image, $dist, $invertScaleQuality);

Finally here image upload script. Which validates given images, once the validation success it will uploads that image to server or else it sends proper error response to the client side.

$data = array();
if( isset( $_POST['image_upload'] ) && !empty( $_FILES['images'] )){
	//get the structured array
	$images = restructure_array(  $_FILES );
	$allowedExts = array("gif", "jpeg", "jpg", "png");

	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
	} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
	} else {
		$ip = $_SERVER['REMOTE_ADDR'];

	foreach ( $images as $key => $value){
		$i = $key+1;
		//create directory if not exists
		if (!file_exists('images')) {
			mkdir('images', 0777, true);
		$image_name = $value['name'];
		//get image extension
		$ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
		//assign unique name to image
		$name = $i*time().'.'.$ext;
		//$name = $image_name;
		//image size calcuation in KB
		$image_size = $value["size"] / 1024;
		$image_flag = true;
		//max image size
		$max_size = 512;
		if( in_array($ext, $allowedExts) && $image_size < $max_size ){
			$image_flag = true;
		} else {
			$image_flag = false;
			$data[$i]['error'] = 'Maybe '.$image_name. ' exceeds max '.$max_size.' KB size or incorrect file extension';

		if( $value["error"] > 0 ){
			$image_flag = false;
			$data[$i]['error'] = '';
			$data[$i]['error'].= '<br/> '.$image_name.' Image contains error - Error Code : '.$value["error"];

			move_uploaded_file($value["tmp_name"], "images/".$name);
			$src = "images/".$name;
			$dist = "images/thumbnail_".$name;
			$data[$i]['success'] = $thumbnail = 'thumbnail_'.$name;
			thumbnail($src, $dist, 200);
			$sql="INSERT INTO images (`id`, `original_image`, `thumbnail_image`, `ip_address`) VALUES (NULL, '$name', '$thumbnail', '$ip');";
			if (!mysqli_query($con,$sql)) {
				die('Error: ' . mysqli_error($con));

	echo json_encode($data);

} else {
	$data[] = 'No Image Selected..';




Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni[at]

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

  • Sreenivas Prince

    I like this tutorials…

  • kumarramesh2020

    why only 20 images are uploaded

  • pls check max upload file size in your php.ini file….

  • developer

    Please Explain how to add, re size image when it’s uploading, With this image upload script file?. Thank You and this is excellent tutorial !.

  • After image is uploaded, we are calling thumbnail($src, $dist, 200); function to do resize. As a parameter to the function we are passing uploaded image url, resize image name and height/weight of the image to be resized.

    In thumbnail() function , I get image extension (jpg, png and etc..) and find height from the width you sent. Finally using PHP GD library to do resizing of the image.

    Also refer this tutorial….

  • Era

    Glad I found this. Everything works but I wonder how to change the destination folder for the uploaded images? Changing the BASE_PATH does not seem to affect this. Am I missing something?

  • hi. upload the script at my server. when i click the upload button, the image doesnt upload to the server or appear (preview) like yours. i already insert my db name, username & password. hope you can help me with my problems. thanks

  • pls change base_path in config.php file.. this will fix the issue…

  • AB

    Is it possible to upload it and make also a thumbnail and put that also in the same record?

  • Yes you can…..

  • AB

    sorry, didn’t saw the code where it actually happens..sorry 🙂

  • thumbnail($src, $dist, 200);
    $sql=”INSERT INTO images (`id`, `original_image`, `thumbnail_image`, `ip_address`) VALUES (NULL, ‘$name’, ‘$thumbnail’, ‘$ip’);”;
    if (!mysqli_query($con,$sql)) {
    die(‘Error: ‘ . mysqli_error($con));

    this will save thumbnail image name to db after thumbnail generated for the uploaded image.

  • Joseph Kiwan Haddad

    Great script! Thank you… I just have one question, some images are being rotated clockwise – how can I prevent this?

  • Samitha Salinda

    Thank you.. Great script!.

    1. how to changing thumbnail image height and thumbnail image save another folder (thumbnail folder).

    2. i want to insert to database some field information (ex input type= text ) . How this

  • Im using your script in my page. The images are uploaded correctly and inserted in database. But when i clik the upload button it jumps from my page to ajax.php and just shows
    Also when i return to my form page Firebug shows me “TypeError: $(…).ajaxForm is not a function”

  • Григорий Чайко

    Thank you how to do to be able to upload up to 4 pictures.
    1 + 3
    2 + 2
    3 + 1
    4, and then switch to another page
    We need to do a counter downloaded images.

  • L. Vinci

    Hello, great script and is exactly what I looking for. How I can limit image upload? Eg I want upload only 5 Images, bulk or single is not important. It can be possible?

  • LPe

    Did you find a solution for this? I am having the same problem.

  • Deepak Yadav

    Great Script, exactly what I am searching for. Thank You.
    I want to display the thumbnails with a border. How can I do that? Please help me

  • Developer

    Hi, i want to upload another image with another resolution 800px, i used thumbnail($src, $dist, 800); and created copy paste of the thumbnail() function and changed width and destination, but it replace with previous resolution ..How to upload another resolution image beside this ?

  • Developer

    I need
    thumbnail($src, $dist, 200); and
    thumbnail_another($src, $dist, 800);

    How to do ?


    Hi, Can I Create folder name by ID when upload record?

  • ReverseEMF

    I hit upon this site via a Google search for help with resizing images on the client side BEFORE uploading the image(s). I want to upload images from a smartphone for use in a website/Facebook. As such, they don’t need to be full resolution. Uploading full resolution images takes a great deal of time, especially if they are numerous. Thus, I wish to reduce their size at the client (probably using Javascript) and then, upload them using AJAX (and then save them in a database, echo them back as a preview on the client, etc.)

    So, can you do that? [Challenge]

    BTW: I actually achieved this, once, around 2 years ago. Then I put the project aside and dusted it off presently and now, for some reason, it’s broken! It was working SO GOOD and now it dies with a Javascript error. I had to do a great deal of research and study to get it to work the first time, and now, to fix it, I would have to relearn all this stuff I have forgotten. So, I know it’s possible! Can you do it?

    In fact, if you DO, in the next week or so, I promise I’ll become a Premium member for at least a year! Shoot me an email or respond to this post, when you’re done 😉

  • ReverseEMF

    I found “PLUPLOAD”…pretty sure I’m gonna go with that! So, nevermind.

  • ReverseEMF

    Not sure what you mean by “by ID”, But, you can name the folder whatever you want. Just change ‘images’ to whatever in the following code:

    if (!file_exists(‘images’)) {
    mkdir(‘images’, 0777, true);

    and in all the places where the ‘images’ path is used.

  • ReverseEMF

    Change ‘images’ in the following code:

    if (!file_exists(‘images’)) {
    mkdir(‘images’, 0777, true);

    and in all the places where the BASE_PATH/images path is used. Like, here:

    move_uploaded_file($value[“tmp_name”], “images/”.$name);
    $src = “images/”.$name;
    $dist = “images/thumbnail_”.$name;

Get Instant Script Download Access!