PHP File Upload with Progress Bar using jQuery and Ajax

PHP File Upload with Progress Bar using jQuery and Ajax


File uploads are a common feature in web applications but implementing them with progress tracking can be challenging. In this guide, we’ll walk through the process of creating a file upload functionality with a progress bar using PHP, jQuery and ajax. We’ll cover everything from handling file uploads securely to displaying progress to the user in real-time.

This will include basically 3 parts of the code implementation. which are as follows:

  • Frontend (basically HTML section, which interact with the user experience)
  • Backend (to handle the code execution to work as the main part to store the files with error handling and storing the form data)
  • JavaScript/jQuery (Which works as the intermediate between Frontend and Backend to provide smooth workflow and help user to connect with your application more interestingly)

Now, let understand with the help of code below with commented code explanation. Hope you will get this worth reading.

Frontend (Index.php/index.html)

Setting Up the HTML Form (index.html):

  • Begin by creating a standard HTML form to facilitate file uploads.
  • Utilize Bootstrap for structuring the form elements in a visually appealing manner.
  • Include a file input field and a button to trigger the upload process.
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
    <!-- Include Bootstrap CSS -->
    <link rel="stylesheet" href="">
    <div class="container mt-5">
        <h2>Upload File</h2>

        <!-- HTML form for file upload -->
        <form id="fileUploadForm" enctype="multipart/form-data">
            <div class="form-group">
                <input type="file" name="file" id="fileInput" class="form-control-file">
            <button id="uploadBtn" type="button" class="btn btn-primary">Upload</button>
            <div class="progress mt-3" style="display: none;">
                <div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>

            <!-- Container for displaying upload status -->
            <div id="uploadStatus" class="mt-3"></div>
    <!-- Include jQuery -->
    <script src=""></script>
    <!-- Include Bootstrap JS -->
    <script src=""></script>
    <!-- Include script.js for handling form submission -->
    <script src="script.js"></script>

Backend (upload.php)

Implementing the Upload Script (upload.php):

  • Begin by setting up error reporting to display all errors for better troubleshooting.
  • Handle file uploads securely by checking for errors and validating file types.
  • Move the uploaded file to the desired destination directory.
  • Return JSON responses for improved error handling and user feedback.
// Set error reporting to display all errors
ini_set('display_errors', 1);

header('Content-Type: application/json');

$response = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $file = $_FILES['file'];

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $response['message'] = 'File upload error: ' . $file['error'];
    } else {

        // Handle file upload securely
        // Move the uploaded file to the desired destination directory
        // Return JSON responses for error handling and user feedback
        $targetDir = 'uploads/';
        $targetFile = $targetDir . basename($file['name']);
        $fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

        // Check if the file already exists
        if (file_exists($targetFile)) {
            $response['message'] = 'File already exists';
        // Check file size (limit to 5MB)
        elseif ($file['size'] > 5 * 1024 * 1024) {
            $response['message'] = 'File size exceeds the limit of 5MB';
        // Allow only certain file formats
        elseif (!in_array($fileType, ['jpg', 'jpeg', 'png', 'gif'])) {
            $response['message'] = 'Only JPG, JPEG, PNG, and GIF files are allowed';
        } else {
            if (move_uploaded_file($file['tmp_name'], $targetFile)) {
                $response['filename'] = basename($file['name']);
            } else {
                $response['message'] = 'Error moving file to destination directory';
} else {
    $response['message'] = 'Invalid request';

echo json_encode($response);

Jquery/JavaScript (script.js)

Writing jQuery Script for Progress Tracking (script.js):

  • Utilize jQuery to handle form submission and initiate file uploads.
  • Check file formats before initiating the upload process to prevent unnecessary progress updates.
  • Implement a progress bar to visually represent the upload progress to users.
  • Display success or error messages based on the upload status.
$(document).ready(function() {
    $('#uploadBtn').click(function() {
        // Retrieve the selected file

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

        // Check if a file is selected
        if (!file) {
            // Display error message if no file is selected
            $('#uploadStatus').html('<div class="alert alert-danger">Please select a file</div>');

        var allowedFormats = ['jpg', 'jpeg', 'png', 'gif'];
        var fileExtension ='.').pop().toLowerCase();

        // Check if the file format is allowed
        if (allowedFormats.indexOf(fileExtension) === -1) {
            $('#uploadStatus').html('<div class="alert alert-danger">Only JPG, JPEG, PNG, and GIF files are allowed</div>');

        var formData = new FormData($('#fileUploadForm')[0]);

        // Send AJAX request to upload.php for file upload
            url: 'upload.php',
            type: 'POST',
            data: formData,
            dataType: 'json',
            contentType: false,
            processData: false,
            xhr: function() {
                // Create an XMLHttpRequest object to track upload progress
                var xhr = new window.XMLHttpRequest();
                xhr.upload.addEventListener('progress', function(event) {
                    if (event.lengthComputable) {
                        var percent = Math.round((event.loaded / * 100);
                        // Update progress bar with the upload progress
                        $('.progress-bar').css('width', percent + '%').text(percent + '%');
                return xhr;
            success: function(response) {
                // Handle successful upload
                $('#uploadStatus').html('<div class="alert alert-success">File uploaded successfully: ' + response.filename + '</div>');
            error: function(xhr, status, error) {
                // Handle upload errors
                var errorMessage = xhr.responseJSON ? xhr.responseJSON.message : 'Unknown error';
                $('#uploadStatus').html('<div class="alert alert-danger">Error: ' + errorMessage + '</div>');


By following the comprehensive steps outlined in this guide, you can master the art of implementing file uploads with a progress bar using PHP and jQuery. With a deep understanding of each component and meticulous attention to detail, you’ll be well-equipped to create robust and user-friendly file upload functionalities for your web applications.

You can get more details about ajax event handling here.
To get to know more about other jQuery topics, you can check these articles too.

Please follow and like us:

Related Posts

Leave a Reply