Uploading multiple images is a common requirement in web applications. Traditionally, submitting an image upload form reloads the page, which can interrupt the user experience.
In this tutorial, we will learn how to upload multiple images without page refresh using AJAX and PHP. The implementation uses jQuery AJAX to send selected images to a PHP script in the background, allowing users to upload files without reloading the page.
The interface also displays a loading spinner while the upload is processing, shows upload progress, validates selected images, and displays previews of successfully uploaded images.
In this tutorial, we will create a simple web page that allows users to select multiple images and upload them without refreshing the page. The uploaded images will be stored in the uploads/ directory on the server with randomly generated names to avoid filename conflicts.
Take a look at the file structure for this tutorial:
upload_multiple_images/ ├── index.html ├── upload.php ├── style.css └── uploads/
Here is a brief overview of the files & folders used in this tutorial:
index.html: The main HTML file containing the upload form and the interface for selecting and previewing images. Contains the image upload form, drag-and-drop area, loading spinner, progress bar, and JavaScript AJAX functionality.upload.php: The PHP script that handles the image upload, validates the uploaded images, saves them to the server, and returns a JSON response.style.css: The CSS file for styling the upload form, progress bar, and image previews.uploads/: The directory where uploaded images will be stored. The PHP script creates this directory if it does not exist and the server permits it.The index.html file contains a multiple-image upload form with a drag-and-drop area, a file input, and a submit button. It also includes sections for displaying selected images (file list with sizes), upload progress (in percentage), and uploaded image previews.
First, create the HTML structure for the upload form: Including a file input for selecting images, a drag-and-drop area, and a submit button. The form will also have sections for displaying selected images, upload progress, and uploaded image previews.
<!-- Upload form -->
<form id="upload-form" action="upload.php" method="post" enctype="multipart/form-data" novalidate>
<!-- File picker and Drag-and-drop area -->
<div class="drop-zone" id="drop-zone">
<svg class="upload-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true">
<path d="M12 16V4m0 0L7.5 8.5M12 4l4.5 4.5M5 14v4.5A1.5 1.5 0 0 0 6.5 20h11a1.5 1.5 0 0 0 1.5-1.5V14" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
<p class="drop-title">Drag images here</p>
<p class="drop-hint">or</p>
<label class="choose-button" for="image-input">Choose images</label>
<p class="limits">JPG, PNG, GIF, or WebP · up to 10 images · 5 MB each</p>
<input id="image-input" name="images[]" type="file" accept="image/jpeg,image/png,image/gif,image/webp" multiple>
</div>
<!-- Selected images list -->
<section class="selection" id="selection" aria-live="polite" hidden>
<div class="selection-heading">
<h2>Selected images</h2>
<span id="file-count"></span>
</div>
<ul class="file-list" id="file-list"></ul>
</section>
<!-- Upload button & loader -->
<div class="actions">
<button class="button" id="upload-button" type="submit" disabled>Upload images</button>
<div class="loader" id="loader" role="status" aria-live="polite" hidden>
<span class="spinner" aria-hidden="true"></span>
<span>Uploading...</span>
</div>
</div>
<!-- Upload progress bar -->
<div class="progress-wrap" id="progress-wrap" hidden>
<div class="progress-meta"><span>Upload progress</span><span id="progress-value">0%</span></div>
<progress id="progress" value="0" max="100" aria-label="Upload progress">0%</progress>
</div>
<p class="message" id="message" role="status" aria-live="polite" hidden></p>
</form>
<!-- Uploaded images previews -->
<section class="previews" id="previews-section" aria-labelledby="previews-title" hidden>
<h2 id="previews-title">Uploaded images</h2>
<div class="preview-grid" id="preview-grid"></div>
</section>
Include jQuery library: To handle AJAX requests and DOM manipulation, include the jQuery library in your HTML file. You can use a CDN link to include jQuery.
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
JavaScript for handling uploads: Use jQuery to handle the form submission, validate selected images, list selected files with sizes, display upload progress, and show previews of uploaded images. The JavaScript code will send the selected images to the upload.php script using AJAX.
<script>
$(function () {
const maxFiles = 10;
const maxBytes = 5 * 1024 * 1024;
const allowedTypes = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);
const $input = $("#image-input");
const $form = $("#upload-form");
const $button = $("#upload-button");
const $message = $("#message");
const $loader = $("#loader");
const $dropZone = $("#drop-zone");
let uploading = false;
function formatSize(bytes) {
return bytes < 1024 * 1024
? Math.max(1, Math.round(bytes / 1024)) + " KB"
: (bytes / (1024 * 1024)).toFixed(1) + " MB";
}
function showMessage(text, kind) {
$message.removeClass("success error").addClass(kind).text(text).prop("hidden", false);
}
function displayFiles(files) {
const $list = $("#file-list").empty();
$("#file-count").text(files.length + (files.length === 1 ? " image" : " images"));
files.forEach(function (file) {
$("<li>").addClass("file-item")
.append($("<span>").text(file.name))
.append($("<span>").addClass("file-size").text(formatSize(file.size)))
.appendTo($list);
});
$("#selection").prop("hidden", files.length === 0);
$button.prop("disabled", files.length === 0 || uploading);
}
function setFiles(files) {
const selectedFiles = Array.from(files);
const transfer = new DataTransfer();
selectedFiles.slice(0, maxFiles).forEach(function (file) {
transfer.items.add(file);
});
$input[0].files = transfer.files;
displayFiles(Array.from(transfer.files));
if (selectedFiles.length > maxFiles) {
showMessage("Only the first " + maxFiles + " images were selected.", "error");
} else {
$message.prop("hidden", true);
}
}
$input.on("change", function () {
setFiles(this.files);
});
["dragenter", "dragover"].forEach(function (eventName) {
$dropZone.on(eventName, function (event) {
event.preventDefault();
$dropZone.addClass("is-dragging");
});
});
["dragleave", "drop"].forEach(function (eventName) {
$dropZone.on(eventName, function (event) {
event.preventDefault();
$dropZone.removeClass("is-dragging");
});
});
$dropZone.on("drop", function (event) {
const files = event.originalEvent.dataTransfer.files;
setFiles(files);
});
$form.on("submit", function (event) {
event.preventDefault();
if (uploading) return;
const files = Array.from($input[0].files);
if (!files.length) {
showMessage("Choose at least one image to upload.", "error");
return;
}
if (files.length > maxFiles) {
showMessage("You can upload up to " + maxFiles + " images at a time.", "error");
return;
}
const invalid = files.find(function (file) {
return !allowedTypes.has(file.type) || file.size <= 0 || file.size > maxBytes;
});
if (invalid) {
showMessage(invalid.name + " is not a supported image or exceeds the 5 MB limit.", "error");
return;
}
const data = new FormData(this);
uploading = true;
$button.prop("disabled", true);
$loader.prop("hidden", false);
$("#progress-wrap").prop("hidden", false);
$("#progress").val(0);
$("#progress-value").text("0%");
$message.prop("hidden", true);
$.ajax({
url: $form.attr("action"),
method: "POST",
data: data,
processData: false,
contentType: false,
dataType: "json",
xhr: function () {
const xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener("progress", function (progressEvent) {
if (progressEvent.lengthComputable) {
const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100);
$("#progress").val(percent);
$("#progress-value").text(percent + "%");
}
});
}
return xhr;
}
}).done(function (response) {
const uploaded = response.files || [];
uploaded.forEach(function (file) {
const $figure = $("<figure>").addClass("preview");
$("<img>").attr({ src: file.url, alt: file.name, loading: "lazy" }).appendTo($figure);
$("<figcaption>").text(file.name).appendTo($figure);
$("#preview-grid").prepend($figure);
});
$("#previews-section").prop("hidden", uploaded.length === 0);
showMessage(response.message || "Images uploaded successfully.", "success");
$input.val("");
displayFiles([]);
$("#progress").val(100);
$("#progress-value").text("100%");
}).fail(function (xhr) {
const response = xhr.responseJSON;
showMessage(response && response.message ? response.message : "The upload failed. Check your connection and try again.", "error");
}).always(function () {
uploading = false;
$loader.prop("hidden", true);
$button.prop("disabled", !$input[0].files.length);
});
});
});
</script>
The upload.php file will handle the uploaded images, validate them, save them to the server, and return a JSON response indicating success or failure using PHP. The script will check the file types and sizes, generate unique filenames, and create the uploads/ directory if it does not exist.
uploads/ directory with unique filenames.<?php
declare(strict_types=1);
// Define constants for upload limits
const MAX_FILES = 10;
const MAX_FILE_SIZE = 5 * 1024 * 1024;
const MAX_IMAGE_PIXELS = 40000000;
// Respond with a JSON payload and exit
function respond(int $status, array $payload): never
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');
echo json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
exit;
}
// Convert a PHP ini size value (like "2M") to bytes
function configuredSizeInBytes(string $value): int
{
$value = trim($value);
if ($value === '') {
return 0;
}
$unit = strtolower($value[strlen($value) - 1]);
$number = (float) $value;
if ($unit === 'g') {
$number *= 1024;
}
if ($unit === 'g' || $unit === 'm') {
$number *= 1024;
}
if ($unit === 'g' || $unit === 'm' || $unit === 'k') {
$number *= 1024;
}
return (int) $number;
}
// Return a human-readable error message for a file upload error code
function uploadErrorMessage(int $error): string
{
return match ($error) {
UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE => 'A file exceeds the server upload size limit.',
UPLOAD_ERR_PARTIAL => 'A file was only partially uploaded. Please try again.',
UPLOAD_ERR_NO_FILE => 'No image file was received.',
UPLOAD_ERR_NO_TMP_DIR => 'The server upload temporary directory is unavailable.',
UPLOAD_ERR_CANT_WRITE => 'The server could not save an uploaded file.',
UPLOAD_ERR_EXTENSION => 'A server extension stopped the upload.',
default => 'An uploaded file could not be processed.',
};
}
// Validate the request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header('Allow: POST');
respond(405, ['success' => false, 'message' => 'Use POST to upload images.']);
}
// Validate the request size against the server's post_max_size
$postLimit = configuredSizeInBytes((string) ini_get('post_max_size'));
$requestSize = (int) ($_SERVER['CONTENT_LENGTH'] ?? 0);
if ($postLimit > 0 && $requestSize > $postLimit) {
respond(413, ['success' => false, 'message' => 'The selected images exceed the server request size limit.']);
}
// Validate that files were uploaded and are in the expected format
if (!isset($_FILES['images']) || !is_array($_FILES['images']['name'] ?? null)) {
respond(400, ['success' => false, 'message' => 'Choose at least one image to upload.']);
}
// Validate the number of uploaded files
$files = $_FILES['images'];
$names = $files['name'];
$count = count($names);
if ($count < 1 || $count > MAX_FILES) {
respond(400, ['success' => false, 'message' => 'Upload between 1 and ' . MAX_FILES . ' images at a time.']);
}
// Validate that the file arrays are consistent and properly structured
foreach (['type', 'tmp_name', 'error', 'size'] as $key) {
if (
!isset($files[$key])
|| !is_array($files[$key])
|| !array_is_list($files[$key])
|| count($files[$key]) !== $count
) {
respond(400, ['success' => false, 'message' => 'The uploaded file data is invalid.']);
}
}
if (!array_is_list($names)) {
respond(400, ['success' => false, 'message' => 'The uploaded file data is invalid.']);
}
// Define allowed MIME types and their corresponding file extensions and image types
$allowedTypes = [
'image/jpeg' => ['extension' => 'jpg', 'image_type' => IMAGETYPE_JPEG],
'image/png' => ['extension' => 'png', 'image_type' => IMAGETYPE_PNG],
'image/gif' => ['extension' => 'gif', 'image_type' => IMAGETYPE_GIF],
'image/webp' => ['extension' => 'webp', 'image_type' => IMAGETYPE_WEBP],
];
$finfo = new finfo(FILEINFO_MIME_TYPE);
$validFiles = [];
$totalPixels = 0;
// Validate each uploaded file
foreach (array_keys($names) as $index) {
if (
!is_string($names[$index])
|| !is_string($files['tmp_name'][$index])
|| !is_int($files['error'][$index])
|| !is_int($files['size'][$index])
) {
respond(400, ['success' => false, 'message' => 'The uploaded file data is invalid.']);
}
$error = $files['error'][$index];
if ($error !== UPLOAD_ERR_OK) {
respond(400, ['success' => false, 'message' => uploadErrorMessage($error)]);
}
$temporaryPath = $files['tmp_name'][$index];
if (!is_string($temporaryPath) || !is_uploaded_file($temporaryPath)) {
respond(400, ['success' => false, 'message' => 'The uploaded file could not be verified.']);
}
$size = filesize($temporaryPath);
if ($size === false || $size < 1 || $size > MAX_FILE_SIZE) {
respond(400, ['success' => false, 'message' => 'Each image must be no larger than 5 MB and cannot be empty.']);
}
$mimeType = $finfo->file($temporaryPath);
if (!is_string($mimeType) || !isset($allowedTypes[$mimeType])) {
respond(400, ['success' => false, 'message' => 'Only JPEG, PNG, GIF, and WebP images are allowed.']);
}
$imageInfo = getimagesize($temporaryPath);
if (
$imageInfo === false
|| ($imageInfo[2] ?? null) !== $allowedTypes[$mimeType]['image_type']
|| ($imageInfo['mime'] ?? null) !== $mimeType
) {
respond(400, ['success' => false, 'message' => 'One of the selected files is not a valid image.']);
}
$width = (int) $imageInfo[0];
$height = (int) $imageInfo[1];
if ($width < 1 || $height < 1 || $width > MAX_IMAGE_PIXELS / $height) {
respond(400, ['success' => false, 'message' => 'An image has dimensions that exceed the allowed limit.']);
}
$totalPixels += $width * $height;
if ($totalPixels > MAX_IMAGE_PIXELS) {
respond(400, ['success' => false, 'message' => 'The combined image dimensions exceed the allowed limit.']);
}
$validFiles[] = [
'temporary_path' => $temporaryPath,
'extension' => $allowedTypes[$mimeType]['extension'],
'name' => basename((string) $names[$index]),
];
}
// Prepare the upload directory
$uploadDirectory = __DIR__ . DIRECTORY_SEPARATOR . 'uploads';
if (!is_dir($uploadDirectory) && !mkdir($uploadDirectory, 0755, true) && !is_dir($uploadDirectory)) {
respond(500, ['success' => false, 'message' => 'The server could not prepare the upload directory.']);
}
if (!is_writable($uploadDirectory)) {
respond(500, ['success' => false, 'message' => 'The server upload directory is not writable.']);
}
// Save each valid file with a secure random name
$savedFiles = [];
$responseFiles = [];
foreach ($validFiles as $file) {
try {
$storedName = bin2hex(random_bytes(16)) . '.' . $file['extension'];
} catch (Random\RandomException $exception) {
foreach ($savedFiles as $savedFile) {
if (is_file($savedFile) && !unlink($savedFile)) {
error_log('Could not remove a partially saved upload: ' . $savedFile);
}
}
respond(500, ['success' => false, 'message' => 'The server could not securely name an uploaded image.']);
}
$destination = $uploadDirectory . DIRECTORY_SEPARATOR . $storedName;
if (!move_uploaded_file($file['temporary_path'], $destination)) {
foreach ($savedFiles as $savedFile) {
if (is_file($savedFile) && !unlink($savedFile)) {
error_log('Could not remove a partially saved upload: ' . $savedFile);
}
}
respond(500, ['success' => false, 'message' => 'The server could not save all images. Please try again.']);
}
$savedFiles[] = $destination;
$responseFiles[] = [
'name' => $file['name'],
'url' => 'uploads/' . rawurlencode($storedName),
];
}
// Respond with success and the details of the uploaded files
respond(200, [
'success' => true,
'message' => count($responseFiles) . (count($responseFiles) === 1 ? ' image uploaded successfully.' : ' images uploaded successfully.'),
'files' => $responseFiles,
]);
?>
Note that: You can set limitations on the number of files that can be uploaded at once (MAX_FILES), as well as the maximum file size (MAX_FILE_SIZE) and allowed file types ($allowedTypes). This can be done both on the client-side using JavaScript and on the server-side using PHP to ensure that only valid files are processed.
In this tutorial, we learned how to upload multiple images without page refresh using AJAX, jQuery, and PHP. The implementation includes drag-and-drop file selection, a loading spinner, upload progress, client-side and server-side validation, unique filenames, and uploaded image previews.
This approach can be adapted for image galleries, profile photo uploads, product image management, and other PHP applications that need multiple-image upload functionality without a full-page reload.
You can also use the Dropzone.js library for a more advanced and feature-rich drag-and-drop file upload experience. For more advanced features and customization, you can explore the Dropzone.js library, which provides a more robust solution for drag-and-drop file uploads. You can find a detailed guide on implementing Dropzone.js with PHP at Drag and Drop File Upload with DropzoneJS using PHP.
Looking for expert assistance to implement or extend this script’s functionality? Submit a Service Request
💰 Budget-friendly • 🌍 Global clients • 🚀 Production-ready solutions
Great, it works..
How to show upload progress (by process % or process bar)?
Hello please can you help me with multiple images uploading like olx.com
Hello please can you help me with registration images uploading like olx.com
how to upload image and pdf files with two different input type and two different progress bar in ajax and php
Hello, very nice script. How can i style the button in the modal?
Great…
Very nice.. but user registration along with image upload?…it’s a challenge.Regards
Thank you so much. Thanks for sharing.
HI
Would tell me how to show multiple image below the upload box .
I always like to reference tutorials like this. Thanks for taking the time to share. Really well done.
Excellent Code.. 100% working
I’d like to request the ‘remove’ option from displayed photos, before they are uploaded. Any idea when/where we could read your code on that feature? Thanks for the info!
Is possible add progress bar?
Great script. But: Is there a reason why the script is limited to 20 files. I can choose as many as I want. But there are only 20 uploads?! Is it possible tu upgrade?
@FTE Yes, it is possible. You should need to change the max_file_uploads variable value in php.ini file. Please follow this guide – http://www.codexworld.com/how-to-guides/increase-files-upload-limit-in-php/
@FTE Yes, it is possible. You should need to change the max_file_uploads variable value in php.ini file. Please follow this guide – http://www.codexworld.com/how-to-guides/increase-files-upload-limit-in-php/
@CODEX WORLD
i don’t know how to say thanks to you…
i’m a beginner of PHP & i found to many interesting articles here 🙂 🙂
all codes are working perfectly & A BIG THANKS FOR DIRECT DOWNLOAD OPTION FOR CODE 🙂 🙂
<3 u @Codexworld
how i download this tutorial
@Ali Download this tutorial from the above Download link. Please let us know, if need further help.
but how create photo album user interface title and description
Wonderful! Exactly what I was looking for, could you please tell how to insert them into database and retrieve them in the form of a single post, I am having trouble doing so, Thank You
Sir please tell me how to create boostrap thumbnails gallery with php pagination…
Hi! it seems that the downloadable version of this does not append to the first uploaded batch of images, it replaces them and display only the newly selected images unlike the demo which appends the newly uploaded to the already uploaded images. thanks. Can we know how to do that?
hai it was nice post ..but i need some help in it .how can we create image album ..when we upload multi images it should save like album ..can u say how can we do it ..thanks in advanced i hope u ll get me out from this
really nice code but i faced one issue i download the script and run into localhost when i upload a one image its show correctly but when i upload second image so first image is replace.i dont want like that,your demo is work correctly i want similar like that please help me
hiii
thanx
it is possible to add the file up loader progress-bar in that code…
Hi, this tutorial is exactaly what i need.
I have a problem, when i try to upload 5 o more images, show a error message:
Notice: Undefined index: image_form_submit in C:\wamp\www\upload\upload.php on line 2
Someone has the same problem? help me please.
You can avoid this error easily. Just remove the below condition into the
upload.phpfile.if($_POST['image_form_submit'] == 1) { }Great, it works..
is it anyway to rename the image file before it upload?
Yes possible. Just modify the
$target_filevariable value like the following.time()is used for adding timestamp to beginning of the image name. You can replace the timestamp with your desire file name.If you want any other modification, please comment here. We are happy to help our users.
great work thank You!!
That’s great code. Thank you.
Could you please add remove option into code?
Thanks Serkan.
We will release the new version with the remove option shortly. Please subscribe our newsletter for receive the new version of this post at your inbox.
Great, great..helps a lot!
Great tutorial bro. I like it.