AJAX Image Upload In PHP (Very Simple Examples)

Welcome to a tutorial on how to AJAX upload an image in PHP. The Stone Age of the Internet is long over, and gone are the days when we have to reload the entire page to upload a file. Let us walk through simple examples of using AJAX to upload images in this guide – Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TLDR – QUICK SLIDES

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Access 1-upload.html or 2-upload.html in the browser.
  • Captain Obvious – Use http:// and not file://.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

SCREENSHOT

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

PHP AJAX IMAGE UPLOADE

All right, let us now get into the examples of uploading images with AJAX.

 

EXAMPLE 1) SINGLE IMAGE UPLOAD

1A) THE HTML

1a-upload.html
<form id="upForm" onsubmit="return up();">
  <input type="file" accept="image/*" name="upFile" required>
  <input type="submit" value="Upload">
</form>

No nasty surprises here, this is just a regular Joe HTML <form> with a single <input type="file"> field. Just take note that we are using Javascript up() to handle the file upload.

 

1B) THE JAVASCRIPT

1b-upload.js
function up () {
  // (A) GET SELECTED IMAGE
  var data = new FormData(document.getElementById("upForm"));
 
  // (B) AJAX UPLOAD
  fetch("1c-upload.php", { method:"POST", body:data })
  .then(res => res.text())
  .then(txt => alert(txt))
  .catch(err => console.error(err));
  return false;
};

Yep. That’s all the “confusing code” to do an AJAX upload.

  • var data = new FormData(HTML FORM) Get the selected file from the HTML form.
  • fetch("1c-upload.php", { method:"POST", body:data }) Uploads the selected file to the server.
  • Lastly, return false to prevent the default form submission and reloading of the page.

P.S. If you do not know fetch() and arrow functions var FUNCTION = () => {}, I will leave some links and a quick crash course in the extras section below.

 

 

1C) PHP UPLOAD HANDLER

1c-upload.php
<?php
$src = $_FILES["upFile"]["tmp_name"];
$dst = $_FILES["upFile"]["name"];
echo move_uploaded_file($src, $dst) ? "OK" : "ERROR" ;

Finally in PHP, we just move the uploaded file out of the temporary folder. The end.

 

EXAMPLE 2) MULTIPLE IMAGES UPLOAD

2A) THE HTML

2a-upload.html
<!-- (A) UPLOAD FORM -->
<form id="upForm" onsubmit="return up.add();">
  <input type="file" accept="image/*" id="upFile" required multiple>
  <input type="submit" value="Upload" id="upGo" disabled>
</form>
 
<!-- (B) UPLOAD STATUS -->
<div id="upStat"></div>

How about uploading multiple files at once? This is pretty much the same HTML form, except for:

  • <input type="file" multiple> File field now accepts multiple files.
  • <div id="upStat"> An empty container to show the upload status.

 

2B) THE JAVASCRIPT

2b-upload.js
var up = {
  // (A) INIT
  upForm : null, // html form
  upFile : null, // html file selector
  upGo : null,   // html submit button
  upStat : null, // html status display
  queue : [],    // upload queue
  init : () => {
    up.upForm = document.getElementById("upForm");
    up.upFile = document.getElementById("upFile");
    up.upGo = document.getElementById("upGo");
    up.upStat = document.getElementById("upStat");
    up.upGo.disabled = false;
  },
 
  // (B) ADD TO UPLOAD QUEUE
  add : () => { 
    // (B1) DISABLE SUBMIT BUTTON
    up.upGo.disabled = true;
 
    // (B2) GET FILES + RESET FIELD
    for (let f of up.upFile.files) { up.queue.push(f); }
    up.upForm.reset();
 
    // (B3) AJAX UPLOAD
    up.ajax();
    return false;
  },
 
  // (C) AJAX UPLOAD
  ajax : () => {
    // (C1) APPEND FIRST FILE IN QUEUE
    var data = new FormData();
    data.append("upFile", up.queue[0]);
 
    // (C2) UPLOAD
    fetch("2c-upload.php", { method:"POST", body:data })
    .then(res => res.text())
    .then(txt => {
      // (C2-1) SHOW UPLOAD STATUS
      up.upStat.innerHTML += `<div>${up.queue[0].name} - ${txt}</div>`;
 
      // (C2-2) NEXT FILE
      up.queue.shift();
      if (up.queue.length!=0) { up.ajax(); }
      else { up.upGo.disabled = false; }
    })
    .catch(err => {
      // (C2-3) ERROR!
      up.upStat.innerHTML += `<div>${err.message}</div>`;
      console.error(err);
    });
  }
};
window.onload = up.init;

This will probably scare beginners away, but keep calm and look closely.

  1. On window load, up.init() will run. All it does – Get HTML elements.
  2. When the form is submitted, up.add() will run. What it does – Put the selected files into up.queue array and start the ajax upload.
  3. up.ajax() Captain Obvious, upload the first file in the queue.

In short, the reason why we are doing this is – AJAX is asynchronous. To prevent a flood of 9999 concurrent uploads all at once, we create a queue to upload one by one instead.

 

 

2C) PHP UPLOAD HANDLER

2c-upload.php
<?php
$src = $_FILES["upFile"]["tmp_name"];
$dst = $_FILES["upFile"]["name"];
echo move_uploaded_file($src, $dst) ? "OK" : "ERROR" ;

See any difference here? Hint: There’s none.

 

EXTRA BITS & LINKS

That’s all for this project, and here is a small section on some extras that may be useful to you.

 

CRASH COURSE – ARROW FUNCTIONS

// (A) YOU ALREADY KNOW THIS
function twice (a) { return a * 2; }

// (B) WE CAN ALSO DO THIS
var twice = function (a) { return a * 2; };

// (C) IN MODERN JS, WE "SHORTHAND" IT TO AN ARROW FUNCTION
var twice = (a) => { return a * 2; };

// (D) IF THERE IS ONLY 1 PARAMETER & RETURN, WE CAN FURTHER SHORTEN IT
var twice = a => { return a * 2; };
var twice = a => a * 2;

 

 

RESTRICTING THE IMAGE SIZE & TYPE

Yes, we can set accept="EXTENSIONS" in the HTML. But take note that any code ninja can use the developer’s console to change the HTML and bypass the checks. It is best to also implement your file size/type restrictions in PHP. See the links below.

 

COMPATIBILITY CHECKS

The examples will work on all modern browsers.

 

LINKS & REFERENCES

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEATSHEET

PHP AJAX Image Upload (Click To Enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

2 thoughts on “AJAX Image Upload In PHP (Very Simple Examples)”

  1. Great Script
    I think helpful would be if you include a file-size limiter to avoid uploading huge images… as most people who will use your script… have NO Clue how to add it… 🙂
    Maybe I overlooked it but I didn’t see were it checks IF File already exits ?!
    I use this…
    // Check if exists
    if (file_exists($target_file)) {
    echo “OpsWe GOT this File already!.”;
    $uploadOk = 0;
    }

    // Check size
    if ($_FILES[“fileToUpload”][“size”] > 7250000) {
    echo “Ouch!!!Your File-Size is too large.”;
    $uploadOk = 0;
    }

Leave a Comment

Your email address will not be published. Required fields are marked *