Web20 University

How To Create a File Upload Progress Bar with PHP

Last edited on
Get up to 65% Off Hosting with FREE SSL & FREE Domains!

* Web 2.0 University is supported by it's audience. If you purchase through links on our site, we may earn an affiliate commision.

When building a web application, offering a smooth user experience during file uploads is definitely something to consider as you need to let users know that they have succesfully uploaded their files.

This is especially true for large file uploads.

Users expect this feedback, and a progress bar is an effective way to provide this.

This post will guide you through creating a file upload progress bar in PHP, exploring multiple approaches and highlighting tools and libraries that simplify the process.


Outline

  1. Introduction
  2. Approaches to Creating a File Upload Progress Bar in PHP
    • JavaScript and PHP with AJAX
    • Using HTML5 Features
  3. Using PHP Libraries for File Upload Progress
    • An Overview of Relevant Libraries
    • Example Implementation with a Library
  4. Step-by-Step Guide: Building Your Own
  5. Conclusion
  6. Additional Resources

Introduction

Uploading files is a common task in web applications, but a large file with no progress feedback can frustrate users if the page is just spinning when the file upload is in progress or even worse it looks like the upload has just failed!

A file upload progress bar in PHP bridges this gap by providing real-time updates by notifying the user visually that the upload is still in progress.

In this post, we’ll look at several ways to implement a progress bar and use popular PHP tools to streamline the process.


Approaches to Creating a File Upload Progress Bar in PHP

1. JavaScript and PHP with AJAX

One of the most popular approaches involves using JavaScript with AJAX to send files to the server while displaying progress updates. Here’s how it works:

  • JavaScript tracks the file upload using the XMLHttpRequest API.
  • The progress bar updates dynamically based on the progress event from the XMLHttpRequest.
  • PHP processes the file on the server and returns the upload status.

2. Using HTML5 Features

HTML5 introduced the progress element and the FormData object, making it easier to build progress bars:

  • Use the <progress> tag to display upload progress.
  • JavaScript interacts with the upload property of XMLHttpRequest to handle the progress.

Using PHP Libraries for File Upload Progress

Some PHP libraries and packages simplify implementing a file upload progress bar in PHP. Let’s explore a couple of options:

1. FineUploader

FineUploader is a JavaScript library that integrates seamlessly with PHP. It supports drag-and-drop uploads and provides built-in progress bar functionality.

2. BlueImp’s jQuery File Upload

BlueImp’s solution is a robust library that supports chunked uploads, progress bars, and server-side integration with PHP.

Example Implementation with BlueImp:

  • Install the package using a package manager or download the files.
  • Configure the server-side script to handle file uploads using PHP.
  • Integrate the provided JavaScript into your front end to enable progress tracking.

Step-by-Step Guide: Building Your Own File Upload Progress Bar

Below is a practical example using JavaScript and PHP with AJAX.

Step 1: HTML Frontend

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload with Progress Bar</title>
</head>
<body>
    <form id="uploadForm" enctype="multipart/form-data">
        <input type="file" name="file" id="file" required>
        <button type="submit">Upload</button>
    </form>
    <progress id="progressBar" value="0" max="100" style="width: 100%;"></progress>
    <div id="status"></div>
    
    <script src="upload.js"></script>
</body>
</html>

Step 2: JavaScript (upload.js)

document.getElementById('uploadForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const file = document.getElementById('file').files[0];
    const formData = new FormData();
    formData.append('file', file);

    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'upload.php', true);

    xhr.upload.addEventListener('progress', function(e) {
        const percent = (e.loaded / e.total) * 100;
        document.getElementById('progressBar').value = percent;
        document.getElementById('status').innerText = `Uploaded ${Math.round(percent)}%`;
    });

    xhr.onload = function() {
        if (xhr.status === 200) {
            document.getElementById('status').innerText = 'Upload complete!';
        } else {
            document.getElementById('status').innerText = 'Error during upload.';
        }
    };

    xhr.send(formData);
});

Step 3: PHP Backend (upload.php)

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($_FILES['file']['name']);

    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
        echo 'File uploaded successfully.';
    } else {
        http_response_code(500);
        echo 'File upload failed.';
    }
}

Conclusion

Creating a file upload progress bar in PHP enhances user experience, making file uploads smooth and efficient. Whether you build one from scratch or use a library like BlueImp, this feature is a valuable addition to your application.


Additional Resources

Get up to 65% Off Hosting with FREE SSL & FREE Domains!