This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Every 1 second delay costs up to 20% conversions. Learn how to fix it [Free • Mar 10–11]. Save My Spot→

How to Add a File Upload Feature in PHP With jQuery AJAX

Updated on February 20, 2026

11 Min Read
php image upload

Key Takeaways

  • Use PHP and jQuery together to enable smooth, AJAX-based file uploads without page reloads.
  • Always validate file types and sizes to protect your server from unwanted uploads.
  • Sanitize filenames to prevent security risks like path traversal attacks.
  • Enhance user experience with real-time progress indicators and upload status messages.
  • Store uploaded file details securely and optionally use SQLite for lightweight database logging.

Letting users upload files is a common feature across many websites—whether it’s images, PDFs, or other documents. If you’re building something that needs this, learning how to set it up with PHP and jQuery can save you a lot of time and headaches.

PHP makes file handling pretty straightforward. And when you combine it with jQuery and AJAX, you can make the upload experience feel seamless without needing a page reload.

In this walkthrough, we’ll start with a simple version of a PHP file upload tutorial and gradually build on it—adding file type and size checks, filename cleanup, a progress bar, and even a small gallery to preview uploaded files.

Let’s get started.

Prerequisites

Before we dive in, here’s what you’ll need:

  • A live server or a local server:
    • You can use XAMPP or MAMP for local development (this includes Apache, MySQL, and PHP out of the box).
    • In this tutorial, I’ll be using Cloudways to deploy my server and app online, which takes away the need for local setup and provides an easy-to-use platform with a built-in stack.
  • A way to access your server files:
    • I’m using FileZilla to upload and manage files on my server.
  • Basic knowledge of HTML, PHP, and jQuery. Even if you don’t, I’ll walk you through every step.

Database (optional): We’ll use SQLite later in the tutorial to log uploaded file info, so you don’t need a full MySQL setup.

For this tutorial, we’ll utilize Cloudways to launch a server with a deployed WordPress application. However, our focus will be on creating a standalone PHP feature.

What We’re Building?

We’ll build a simple web interface where a user can upload a file (e.g., image, PDF, etc.), and the file will be stored on the server—without refreshing the page. We’ll use:

  • HTML for the formjQuery for capturing the file input and sending it via AJAX
  • PHP on the backend to handle the upload
  • FileZilla to upload files to your Cloudways server

At the end, we’ll load the form in the browser and upload a file to make sure it all works.

Part 1: Setting Up the Basic File Upload

We’re starting with a simple file upload system. You’ll have a webpage where users can select a file and click upload. The file will be sent to the server using AJAX without refreshing the page.

Step 1: Create Your Folder Structure

In your Cloudways application (or local public_html), create a new folder for this project. I’ll call mine file-upload.

Inside file-upload, create these three things:

  1. index.html — Our main frontend file.
  2. upload.php — The backend script that handles uploads.
  3. uploads/ — A folder to store the uploaded files.

You can create this structure using FileZilla by navigating to public_html, right-clicking to create a directory (file-upload), and then creating the files and folders inside it.

File Upload

Step 2: Build the HTML Form (index.html)

Let’s write the upload interface. This is the file users will interact with. Let’s edit the index.html file we created earlier and paste this code into it:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Simple File Upload</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>

<body>

<h2>Upload a File</h2>

<input type="file" id="fileInput">

<button id="uploadBtn">Upload</button>

<div id="status"></div>

<script>

$('#uploadBtn').on('click', function () {

var file = $('#fileInput')[0].files[0];

if (!file) {

$('#status').text('Please select a file.');

return;

}

var formData = new FormData();

formData.append('file', file);

$.ajax({

url: 'upload.php',

type: 'POST',

data: formData,

processData: false,

contentType: false,

success: function (response) {

$('#status').html(response);

},

error: function () {

$('#status').text('An error occurred while uploading.');

}

});

});

</script>

</body>

</html>

This is the front of our uploader—just a basic form with a file input and a button. We’ll also load jQuery so we can use AJAX.

What’s happening here?

We’re using jQuery to listen for a button click, grab the selected file, and send it to the server using AJAX. This keeps the page from reloading and gives a smoother experience.

Step 3: Handle the Upload in PHP (upload.php)

This script receives the file from AJAX and moves it to the uploads/ folder.

<?php

if (isset($_FILES['file'])) {

$targetDir = "uploads/";

$filename = basename($_FILES["file"]["name"]);

$targetFilePath = $targetDir . $filename;

if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)) {

echo "File uploaded successfully: " . htmlspecialchars($filename);

} else {

echo "Failed to upload file.";

}

} else {

echo "No file received.";

}

?>

Step 4: Testing the Basic Upload

  • Select a file and click the Upload button.

Select a file and click the Upload button.

  • You should see a success message, and the file should appear in the uploads directory.

Uploaded File

Uploaded File

Host PHP Websites with Ease [Starts at $11 Credit]

  • Free Staging
  • Free backup
  • PHP 8.4
  • Unlimited Websites

TRY NOW

Part 2: Upgrading the File Upload (Advanced Version)

Now that we’ve got the basic file upload working, let’s take things up a notch. What we built before was the “proof of concept” — it uploads a file and tells us it worked (or didn’t).

That’s fine for starters, but in the real world, we need more control, security, and feedback.

So in this part of the guide, we’re going to improve our uploader by:

  • Limiting file types (so users can’t upload just anything)
  • Enforcing a size limit
  • Sanitizing filenames (because users can be sneaky)
  • Showing a live upload progress bar
  • Displaying a gallery of uploaded files
  • Storing file info in a database (we’ll use SQLite — easier than MySQL)
  • Securing the upload folder
  • Optionally adding reCAPTCHA for spam protection

This section assumes you’ve already set up your project with the basic version (with index.html, upload.php, and an uploads/ folder). If you haven’t, go back and follow Part 1 first.

Restrict uploads to specific file types (images & PDFs)

Right now, users can upload any file — .exe, .php, .zip, you name it. That’s not safe. We’ll fix that by checking the MIME type of the uploaded file. Only JPEG, PNG, GIF, and PDF files should be allowed.

Open your upload.php file and replace the entire code with this:

<?php

if (isset($_FILES['file'])) {

$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];

$fileType = $_FILES["file"]["type"];

if (!in_array($fileType, $allowedTypes)) {

echo "Only JPG, PNG, GIF images and PDFs are allowed.";

exit;

}

$targetDir = "uploads/";

$filename = basename($_FILES["file"]["name"]);

$targetFilePath = $targetDir . $filename;

if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)) {

echo "File uploaded successfully: " . htmlspecialchars($filename);

} else {

echo "Failed to upload file.";

}

} else {

echo "No file received.";

}

?>

What’s happening here?

We’re checking the uploaded file’s type. If it doesn’t match one of the types in our allowed list, we stop the upload and show a message.

Let’s Test!

So if I try to upload an unsupported file, I’ll get a message saying “Only JPG, PNG, GIF images and PDFs are allowed.”

Multiple files

But if I upload a PNG file, for example, it should upload right away.

Uploaded Multiple file

Add a file size limit (Max 5MB)

To avoid huge files clogging up your server, we’ll limit uploads to 5 MB.

Open your upload.php again, and before the move_uploaded_file() line, add this code:

$maxSize = 5 1024 1024; // 5MB

if ($_FILES["file"]["size"] > $maxSize) {

echo "File is too large. Max allowed size is 5MB.";

exit;

}

Like so:

File is too large code

Why are we doing this?

A user might accidentally (or intentionally) upload a 200MB video. This limit prevents that and helps your site stay fast and responsive.

Let’s Test!

To test it out, I’ll add an image that is 10MB in size, greater than the 5MB limit we added.

10mb file

In this case, I’ll see the “File is too large. Max allowed size is 5MB” message. Like so:

Maximum Upload Size

Sanitize the filename

When users upload files, they can name them anything — from something harmless like profile_picture.jpg to something super messy like:

../../../evil<script>.php

or

my*resume#final@@@!!v9.pdf

We don’t want that chaos ending up in our server’s file system. Not only does it look messy, but it can open the door to security vulnerabilities (like path traversal attacks, where someone tries to jump out of the intended folder).

To address this, we can implement file sanitization.

Find this line in upload.php:

$filename = basename($_FILES["file"]["name"]);

Basename Code

And replace it with:

$filename = preg_replace("/[^A-Za-z0-9\.\-_]/", '', basename($_FILES["file"]["name"]));

Basename new code

What this does:

It strips out any character that’s not a letter, number, dot, dash, or underscore. That keeps things clean and prevents path exploits.

Take a look at the table below for a better understanding:

Original File Name After Sanitization
my resume (final)!!v3.pdf myresumefinalv3.pdf
../../../secret.php secret.php
hello@#world!.jpg helloworld.jpg
invoice_2024^%$.pdf invoice_2024.pdf

Let’s Test!

To test, let’s upload a file called “weird^%$#@!.pdf”.

PDF upload

Now, if we go to the uploads folder, you’ll notice how all the weird symbols disappear.

PDF path

Add a progress bar with jQuery + AJAX

We’ll now improve the user experience. Instead of clicking upload and hoping something happened, we’ll show live progress.

Why use jQuery and AJAX here?

AJAX allows us to upload the file in the background without reloading the page. jQuery makes the syntax easier and cleaner.

In your index.html, find the <script> tag at the bottom and replace the entire thing with this:

<script>

$('#uploadBtn').on('click', function () {

var file = $('#fileInput')[0].files[0];

if (!file) {

$('#status').text('Please select a file.');

return;

}

var formData = new FormData();

formData.append('file', file);

var xhr = new XMLHttpRequest();

xhr.open("POST", "upload.php", true);

xhr.upload.onprogress = function (e) {

if (e.lengthComputable) {

var percent = Math.round((e.loaded / e.total) * 100);

$('#status').html("Uploading: " + percent + "%");

}

};

xhr.onload = function () {

if (xhr.status == 200) {

$('#status').html(xhr.responseText);

} else {

$('#status').text('Upload failed.');

}

};

xhr.send(formData);

});

</script>

Check the GIF below:

Let’s Test!

Now, if I upload a file, we can see a progress bar. Check the GIF below:

Upload a New File

Now your users can see the upload progress in real time for a much smoother experience.

Display all uploaded files below the form

We’ll now show a list of all uploaded files in a mini gallery right below your upload form, and we’ll make sure it updates automatically every time a new file is uploaded.

This is a great feature if you want users (or yourself) to see the list of files that are already sitting in your uploads/ folder — without needing to refresh the page.

Here’s how we can achieve this:

1. Open index.html and below the #status div, add this:

<div id="gallery"></div>

Gallery code

2. Create a new file in the same folder called list_uploads.php.

List file upload

And paste this inside:

<?php

$dir = 'uploads/';

$files = scandir($dir);

foreach ($files as $file) {

if ($file === '.' || $file === '..') continue;

echo "<p><a href='uploads/$file' target='_blank'>$file</a></p>";

}

?>

3. Go back to your <script> in index.html, and update the xhr.onload part like this:

xhr.onload = function () {

if (xhr.status == 200) {

$('#status').html(xhr.responseText);

$('#gallery').load('list_uploads.php');

} else {

$('#status').text('Upload failed.');

}

};

Now what happens:

Every time a file is uploaded, the list below the form updates with a clickable link to that file.

All files uploaded

PHP file uploads acting up?

Share your code and get instant feedback from developers in the Cloudways Reddit Community.

Wrapping Up!

This wraps up our PHP file upload guide. You’ve now got a working file upload feature using PHP and jQuery AJAX, with helpful upgrades like validation, a progress bar, and a live gallery.

These small but important details go a long way in making uploads feel reliable and smooth for users. If you plan to build on this, you’ve got a solid starting point to grow from.

Frequently Asked Questions

Q) Where do uploaded files go in PHP?

A) In PHP, all temporary files, including uploaded files, are stored in the temporary files directory as specified in php.ini. It’s important to note that for uploads, these files may be deleted as soon as the script the file was uploaded to is terminated (so unless you delay that script, you probably won’t see the uploaded file).

Q) How to upload a file in PHP?

A) To upload a file in PHP, use an HTML form with enctype=”multipart/form-data”, then handle the file in PHP with move_uploaded_file(). Make sure file_uploads is enabled in php.ini, and the destination folder has proper permissions.

Q) How to load a PHP file?

A) To load a PHP file, ensure it’s placed inside the htdocs folder (if using XAMPP) or the appropriate web server directory. Then, open a browser and enter http://localhost/yourfile.php. If using a remote server, upload the file and access it via the server’s domain or IP address.

Q) What are $_ files in PHP?

A) $_FILES is a PHP superglobal that stores details about uploaded files, including name, size, type, and temporary location. It is used to handle file uploads via HTML forms. Modern browsers also support uploading entire directories using the webkitdirectory attribute.

Q) How to add a PHP file in HTML?

You can add a PHP file in HTML using include or require statements. These allow you to insert external PHP scripts into your HTML, making your content dynamic. Example:

<?php include ‘file.php’; ?>

Both methods work, but require will cause a fatal error if the file is missing, while include will show a warning and continue execution.

Q) Which is the best PHP library for file uploading?

A) Several file-uploading PHP libraries are available, but the HTML5 File Upload library is considered one of the best. It’s user-friendly and popular among developers because it simplifies tasks like upload file Laravel functionality and validation quickly..

Q) Where can I download the PHP file upload script?

A) You can download the file-uploading script from phpfileuploader.com. This site offers an advanced and easy-to-use file-uploading script that accurately uploads files to the server without refreshing the page. With this script, you can easily upload multiple and new additional files during the upload process.

Q) How do you move uploaded files in PHP?

A) The move_uploaded_file() function can be used to move the uploaded file to a new path/directory. This function allows us to easily relocate files to a new location, even if they are newly uploaded. If the transfer is successful, it returns TRUE; if there’s any exception, it returns FALSE.

Q) What is a file upload feature in PHP?

A) The file upload feature in PHP lets users transfer files from their local device to a web server. It works through an HTML form with an input field, and PHP handles the uploaded file using the $_FILES superglobal, ensuring secure processing and storage.

Q) How does AJAX work for file uploads in PHP?

A) AJAX enables seamless file uploads without refreshing the page. It sends files to the server in the background using JavaScript, often with jQuery’s $.ajax() method or the Fetch API. PHP then processes the file on the server side. This improves user experience by allowing smooth, real-time uploads.

Q) How can I restrict the file size for uploads in PHP?

A) You can restrict file size in PHP by setting upload_max_filesize and post_max_size in the php.ini file. Additionally, use PHP code to validate the file size before processing the upload to ensure it meets your limits.

Q) Can I use PHP and jQuery AJAX for drag-and-drop file uploads?

A) Yes, you can use PHP and jQuery AJAX for drag-and-drop file uploads. HTML5’s drag-and-drop API, combined with jQuery and AJAX, allows seamless, real-time uploads without reloading the page. The files are sent to the server asynchronously, where PHP processes and stores them efficiently.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Abdul Rehman

Abdul is a tech-savvy, coffee-fueled, and creatively driven marketer who loves keeping up with the latest software updates and tech gadgets. He's also a skilled technical writer who can explain complex concepts simply for a broad audience. Abdul enjoys sharing his knowledge of the Cloud industry through user manuals, documentation, and blog posts.

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour