Upload Multiple Images Without Page Refresh using AJAX and PHP

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.

Ajax Image Uploader Script Features

  • Upload multiple images in a single request without refreshing the page.
  • Select images using the file picker or drag and drop them into the upload area.
  • Display the selected image filenames and file sizes before uploading.
  • Show a loading spinner and an “Uploading…” message during the upload process.
  • Display upload progress using a progress bar.
  • Validate image formats and file sizes on both the client and server sides.
  • Allow JPEG, PNG, GIF, and WebP images.
  • Limit each upload request to 10 images, with a maximum file size of 5 MB per image.
  • Display success and error messages.
  • Show previews of uploaded images after a successful upload.
  • Generate unique filenames for uploaded images.
  • Provide a responsive interface with accessible status messages.

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.

File Structure

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:

  1. 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.
  2. upload.php: The PHP script that handles the image upload, validates the uploaded images, saves them to the server, and returns a JSON response.
  3. style.css: The CSS file for styling the upload form, progress bar, and image previews.
  4. 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.

Create the HTML Upload Form

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>

PHP Script for Handling Uploads

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.

  • Define constants for maximum file size and allowed file types.
  • The respond() function will be used to send JSON responses back to the client.
  • The configuredSizeInBytes() function will convert the configured size to bytes.
  • The uploadErrorMessage() function will generate error messages for upload failures.
  • Validate each uploaded image for type and size.
  • Save valid images to the uploads/ directory with unique filenames.
  • Return a JSON response with the status of the upload and details of the uploaded images.
<?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.

Conclusion

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

35 Comments

  1. Bee Said...
  2. Cynthia Said...
  3. Cynthia Said...
  4. Rajat Said...
  5. Patrik Iden Said...
  6. Karishma Pathak Said...
  7. Jovan Said...
  8. Dogum Gunu Pastasi Said...
  9. Shubham Said...
  10. Sam Smith Said...
  11. Nir Said...
  12. Steve Goerger Said...
  13. Naruto Said...
  14. FTE Said...
  15. Mohsin Khan Said...
  16. Ali Said...
    • CodexWorld Said...
  17. Taher Said...
  18. Msikkac Said...
  19. Satish Said...
  20. Zhujih Said...
  21. Bharathi Said...
  22. Umesh Chakor Said...
  23. Sehjad Said...
  24. Christian Said...
    • CodexWorld Said...
  25. Cykro Said...
    • CodexWorld Said...
  26. Sampath Said...
  27. Serkan Said...
    • CodexWorld Said...
  28. Boris Said...
  29. Kathy Said...

Leave a reply

construction Need this implemented in your project? Request Implementation Help → keyboard_double_arrow_up