Top

Follow me and receive all the latest free scripts:

By Email:

Categories
Most Popular Posts

Ajax upload multiple images using PHP and jQuery

Ajax upload multiple images using PHP and jQuery

Published October 14, 2014 by , category jQuery

jQueryAjaxUploadImageMultipleForm

jQuery Ajax multiple file upload using PHP

Introduction

If you are looking for multiple image uploader, using PHP, Ajax and jQuery, and without refreshing page, you are at the right place.

I invite you to check my previous tutorial about how to upload single images using jQuery, It's the same kind of system, but for multiple images .

For this tutorial I use my favorite jQuery JavaScript Library of course, and Bootstrap CSS framework for the display, easy to change for your own CSS style sheet.

I have included a cropping function, so for each image uploaded, I store its original size and a thumbnail (160x120 px or 120x160 px depending if it's a landscape or a portrait).

I have also included a string converter. So images with weird name, including characters such as #, @, !, ^, ) etc… are renamed, and these characters are replaced by dash (-).

For the thumbnails I add a small- before the rest of the string.

You are free of course to not use these functions, if you don't need them:

  1. If you don't need a thumbnail,
  2. If you want to simply rename the image by, for example, image-$num-$id.ext, where $num is the image number and $id a unique user id... So let's say you upload 3 photos in one time from the user having the id 12, the first image will be renamed image-1-12.jpg, the second image will be renamed image-2-12.jpg and the third image-3-12.jpg. (It's just an example of what you can do ).

Files architecture

index.php
db.class.php

ajax

tuto-upload-multiple-images.php

jquery

jquery.form.js (jQuery Form Plugin) (Download)

design

upload

There is an "upload" folder. It's where images and thumbnails will be stored

Live demo

For safety reasons and to prevent misuse, datas are not inserted in the database, and images are not stored.

Upload your images Max: 128 Kb/image; jpg, jpeg, png & gif

Database structure sample

id is the "id" (database row number) of the image stored. Notice that I store the date and time when the image has been uploaded (not required of course), the original image and it's thumbnail.

CREATE TABLE IF NOT EXISTS `tc_tuto_upload_image` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `date_ins` date NOT NULL DEFAULT '0000-00-00',
  `hour_ins` time NOT NULL DEFAULT '00:00:00',
  `img_thumb` varchar(255) NOT NULL,
  `img_original` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 ;

Database connection

Page db.class.php. More information about the database connection I use here.

HTML & jQuery code

This is the index.php page (or any page you want the script appears), I put the full page structure. JavaScript is at the end, before </body> markup, with a link to jquery/jquery-1.10.1.min.js and a link to jquery/jquery.form.js.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
<head>
	<title>Ajax upload multiple images using PHP and jQuery</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	
	<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" type="text/css">
</head>

<body>

<div class="container">
	<div class="row">
		
		<div class="col-md-9">
		
			<div id="result"></div>
			
			<form method="post" enctype="multipart/form-data" id="MyImageUploadForm" action="ajax/tuto-upload-multiple-images.php">
				<p><input name="image[]" id="image" type="file" multiple="multiple" /></p>
			</form>
		
		</div>
	
	</div>
</div>

<script type="text/javascript" src="jquery/jquery-1.10.1.min.js"></script>
<script src="jquery/jquery.form.js"></script>
<script type="text/javascript">
	$(function() {
		$('#image').bind('change', function() {
			$("#result").html('<img src="design/loader.gif" alt="" />');
			$('#MyImageUploadForm').ajaxForm({
				target: '#result'
			}).submit();
		});
	});
</script>
	
</body>
</html>

PHP code

It's the ajax/tuto-upload-image.php file, including the crop_img function and the convert_str function. Functions may be placed in another file, a functions.php file if you have one. Don't forget to call this file at the beginning of the code of course with an include('../functions.php');

Lines are commented. You can easily adapt the script and remove what you don't need.

<?php
include('../db.class.php');
$bdd = new db();

$acceptedExtension = Array('image/jpeg', 'image/jpg', 'image/pjpg', 'image/pjpeg', 'image/png', 'image/gif'); // add here allowed extensions
$maxSize = 5000000; //image size max = 5Mb
$destFolder = 'upload/';

echo '<div class="row">'; // Bootstrap CSS Thumbnails
for($i=0; $i<count($_FILES['image']['name']); $i++) { // Loop through each file
	
	$imgType = $_FILES["image"]["type"][$i];
	$imgSize = $_FILES["image"]["size"][$i];
	$imgName = $_FILES["image"]["name"][$i];
	$imgTmpName = $_FILES["image"]["tmp_name"][$i];

	if (in_array($imgType, $acceptedExtension) && $imgSize <= $maxSize && $imgSize != "") { // we test the validity of the image

		$newOriginalImageName = convert_str($imgName); // we give our original photo a new name (we convert the string with the function convert_str below)
		$newThumbImageName = 'small-'.convert_str($imgName); // same we give a name the thumbnail (the same name than the original but starting with "small-")

		if(move_uploaded_file($imgTmpName,"../".$destFolder.$newOriginalImageName)) { // test if the original image is moved on the server
			
			copy("../".$destFolder.$newOriginalImageName, "../".$destFolder.$newThumbImageName); // we copy the origininal image and rename it (it will be our thumbnail)
			chmod ("../".$destFolder.$newThumbImageName, 0777); // we change the chmod so we can crop
					
			// we crop the photo
			list($width, $height, $type, $attr) = getimagesize("../".$destFolder.$newOriginalImageName); // we take the image height and width
			// the crop function is below
			if ($width>$height) { // if the image is landscape style
				crop_img ("../".$destFolder.$newThumbImageName, 160, 120); // we crop and resize 160x120px
			} else { // if the image is portrait style
				crop_img ("../".$destFolder.$newThumbImageName, 120, 160);// we crop and resize 120x160px
			}
			
			// we instert into database; the thumbnail path and the original path
			$upload = $bdd->execute('INSERT INTO tc_tuto_upload_image (date_ins, hour_ins, img_thumb, img_original) VALUES (NOW(), NOW(), "'.$newThumbImageName.'", "'.$newOriginalImageName.'")');
			
			echo '<div class="col-xs-6 col-md-3"><a href="#" class="thumbnail"><img src="'.$destFolder.$newThumbImageName.'" alt="" /></a></div>'; // we send back the thumbnail - check Bootstrap for the CSS
		}

	} else {
		echo '<div class="col-xs-6 col-md-3"><a href="#" class="thumbnail">Error with your image (wrong format or size)!</a></div>';
	}

}
echo '</div>';

// crop function (feel free to adapt)
function crop_img ($image, $thumb_width, $thumb_height) {
	$filename = $image;
	$image = imagecreatefromstring(file_get_contents("$image"));

	$width = imagesx($image);
	$height = imagesy($image);

	$original_aspect = $width / $height;
	$thumb_aspect = $thumb_width / $thumb_height;

	if ( $original_aspect >= $thumb_aspect ) {
	   // If image is wider than thumbnail (in aspect ratio sense)
	   $new_height = $thumb_height;
	   $new_width = $width / ($height / $thumb_height);
	} else {
	   // If the thumbnail is wider than the image
	   $new_width = $thumb_width;
	   $new_height = $height / ($width / $thumb_width);
	}

	$thumb = imagecreatetruecolor($thumb_width, $thumb_height);

	// Resize and crop
	imagecopyresampled($thumb,
					   $image,
					   0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
					   0 - ($new_height - $thumb_height) / 2, // Center the image vertically
					   0, 0,
					   $new_width, $new_height,
					   $width, $height);
	
	return imagejpeg($thumb, $filename, 80);
}

// convert string function (feel free to adapt)
function convert_str($str) {	
	$str = str_replace(
		array(' : ',': ',' !',' ?','!','?','"','\'',', ','(',')',' / ','/',' « ',' » ','  ',' ','&','_', '#'),
		array(  '-', '-',  '',  '', '', '', '', '-', '-', '', '',  '-','-',  '-',  '-', '-','-','-','-', ''),
		$str
	);

	$str = str_replace(
		array('    ','   ','  ',' ','----','---','--'),
		array(    '',   '',  '', '',   '-',  '-', '-'),
		$str
	);
	
	$str = strtolower($str);
	
	return $str;
}
?>

Conclusion

That's it, I hope you enjoy the script and I hope you'll find help and solutions for your own scripts.

As usually, don't hesitate to comment below if you have questions.

Happy coding!

About Simon Laroche
Simon Laroche on Google+
Simon Laroche on Twitter
Simon Laroche on Facebook
Simon Laroche on Pinterest
Simon Laroche on LinkedIn
: I am a Coder, Designer, Webmaster and Expert SEO Consulting, I'm also a wise traveller and an avid amateur photographer. I created the website TipoCode and many others such as Landolia: a World of Photos...

If you need help about this script, please leave a comment below. I reply as much as I can depending of my time, you may also get help from others.
I also offer a paid support, if you are in the need to adapt or create a script...

Leave a comment

Comments (4 comments)

Carl Posted on January 16, 2017
Can i get the source code? Thanks
lalit Posted on May 02, 2016
how i can download source files ?
Simon Laroche
Simon Laroche Posted on July 27, 2015
@Mandy Sandhu: I don't provide source files, all the code is above and working fine as you see (the demo). You may adapt to your site or quickly create the file and copy/paste the code.
Mandy Sandhu
Mandy Sandhu Posted on July 26, 2015
how i can download source files ?