Welcome to a tutorial and example of how to upload an image using AJAX and PHP. The Stone Age of the Internet is long over, and gone are the days where we have to reload the entire page to submit a form.
There are 3 main components to an AJAX-PHP image upload:
- An HTML file upload form.
- Javascript to manage the AJAX image file uploads.
- Server-side PHP script to check and process the image upload.
Let us walk through a simple example 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.
QUICK SLIDES
TABLE OF CONTENTS
DOWNLOAD & NOTES
Firstly, here is the download link to the example code as promised.
QUICK NOTES
- Access
1-upload-form.html
in the browser. - Captain Obvious – Use
http://
and notfile://
.
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.
AJAX IMAGE UPLOADER
All right, let us now get started with the AJAX image uploader.
STEP 1) HTML IMAGE UPLOAD FORM
<!-- (A) UPLOAD FORM -->
<form id="upform" onsubmit="return ajaxup.add();">
<h1>AJAX Upload Demo</h1>
<label for="upfile">Choose an image file:</label>
<input type="file" accept=".png,.gif,.jpg,.webp" id="upfile" multiple required/>
<input type="submit" value="Upload"/>
</form>
<!-- (B) UPLOAD STATUS -->
<div id="upstat"></div>
- No nasty surprises here, this is just a regular Joe HTML form with a single
<input type="file"/>
field. - Also, take note of
<div id="upstat">
, we will be using this to show the status of the uploaded files.
STEP 2) JAVASCRIPT AJAX UPLOAD
var ajaxup = {
// (A) ADD TO UPLOAD QUEUE
queue : [], // upload queue
add : () => {
for (let f of document.getElementById("upfile").files) {
ajaxup.queue.push(f);
}
document.getElementById("upform").reset();
if (!ajaxup.uploading) { ajaxup.go(); }
return false;
},
// (B) AJAX UPLOAD
uploading : false, // upload in progress
go : () => {
// (B1) UPLOAD ALREADY IN PROGRESS
ajaxup.uploading = true;
// (B2) FILE TO UPLOAD
var data = new FormData();
data.append("upfile", ajaxup.queue[0]);
// APPEND MORE VARIABLES IF YOU WANT
// data.append("KEY", "VALUE");
// (B3) FETCH UPLOAD
fetch("3-ajax-upload.php", { method:"POST", body:data })
.then(res=>res.text()).then((res) => {
// (B4) SHOW UPLOAD RESULTS
document.getElementById("upstat").innerHTML += `<div>${ajaxup.queue[0].name} - ${res}</div>`;
// (B5) NEXT FILE
ajaxup.queue.shift();
if (ajaxup.queue.length!=0) { ajaxup.go(); }
else { ajaxup.uploading = false; }
})
.catch((err) => { console.error(err) });
}
};
This looks confusing at first, but keep calm and look carefully.
- When the HTML form is submitted,
ajaxup.add()
will fire up. This basically gets the selected files and appends them into the upload queueajaxup.queue
. ajaxup.go()
is the actual function that does the AJAX upload.- It simply uploads the first file in the queue
ajaxup.queue[0]
. - On upload completion, the file is removed from the queue
ajaxup.queue.shift()
. - The next “upload cycle” then continues until the upload queue is exhausted –
if (ajaxup.queue.length!=0) { ajaxup.go(); }
- It simply uploads the first file in the queue
In short, all the Javascript does is upload one file at a time to prevent a server flood.
STEP 3) PHP IMAGE UPLOAD HANDLER
<?php
// (A) UPLOAD FILE CHECK
$result = "";
if (!isset($_FILES["upfile"]["tmp_name"])) {
$result = "No file uploaded.";
}
// (B) IS THIS A VALID IMAGE?
if ($result=="") {
$allowed = ["bmp", "gif", "jpg", "jpeg", "png", "webp"];
$ext = strtolower(pathinfo($_FILES["upfile"]["name"], PATHINFO_EXTENSION));
if (!in_array($ext, $allowed)) {
$result = "$ext file type not allowed - " . $_FILES["upfile"]["name"];
}
}
// (C) OPTIONAL - DO NOT OVERRIDE FILE ON SERVER
if ($result=="") {
$source = $_FILES["upfile"]["tmp_name"];
$destination = $_FILES["upfile"]["name"];
/*
if (file_exists($destination)) {
$result = "$destination already exist";
}*/
}
// (D) MOVE UPLOADED FILE OUT OF TEMP FOLDER
if ($result=="") {
if (!move_uploaded_file($source, $destination)) {
$result = "Failed to save to $destination";
}
}
// (E) SERVER RESPONSE
echo $result=="" ? "OK" : $result ;
No BS here either, things are straightforward as well.
- Checks if a file is actually uploaded.
- Check if the uploaded file is an accepted image format.
- Check if file already exists on the server. Optional.
- Move the uploaded image file out of the temporary folder.
USEFUL BITS & LINKS
That’s all for this project, and here is a small section on some extras that may be useful to you.
ALLOW ONLY A SINGLE UPLOAD
- Just remove the
multiple
attribute –<input type="file" accept=".png,.gif,.jpg,.webp" id="upfile" required/>
. - Hide the upload form on upload start –
document.getElementById("upform").style.display = "none"
- Best that you show some sort of upload progress though…
- Do whatever you need on upload complete – Enable the upload form again, show a “thank you”, or redirect the user to another page.
SET THE IMAGE TYPE RESTRICTIONS
Yes, there are a ton of different image formats. If you want to change the accepted image formats, set the accept="EXTENSIONS"
in the HTML. Also, remember to update 3-ajax-upload.php
accordingly – $allowed = [EXTENSIONS]
.
LINKS & REFERENCES
- Fetch API – MDN
- FormData API – MDN
- Drag-and-drop file upload – Code Boxx
- Save the image file into the database – Code Boxx
- AJAX Upload With Progress Bar – Code Boxx
- Restrict Upload File Type & Size – Code Boxx
TUTORIAL VIDEO
INFOGRAPHIC CHEATSHEET

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!
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 “Ops…We GOT this File already!.”;
$uploadOk = 0;
}
// Check size
if ($_FILES[“fileToUpload”][“size”] > 7250000) {
echo “Ouch!!!Your File-Size is too large.”;
$uploadOk = 0;
}
https://code-boxx.com/restrict-file-type-size-php-upload/