File Uploading with Progress Bar using PHP and JavaScript Tutorial

In this tutorial, I will demonstrate how to create a straightforward web application featuring a File Uploads with a Progress Bar. Throughout this article, I'll provide code snippets along with brief explanations to facilitate your understanding of the file upload process. The tutorial is created to serve as a valuable resource for students and beginners in PHP and JS programming languages, enabling them to enhance their knowledge and web application development skills.

Understanding the File Upload Feature

File uploading is a common functionality for transferring files across networks, particularly over the internet. This feature is often integrated into applications, allowing users to upload files to the server for convenient access from anywhere. Prominent examples of web and mobile applications employing this feature include Google Drive and Dropbox. These applications primarily serve the purpose of Storing and Sharing Documents or Files Online.

In certain instances, file uploading is incorporated to support other aspects of applications, such as Social Media Applications, which often includes User Profile Images and Sharing of Videos and Images.

Let's Get Started

By the end of this tutorial, we will have created the following files for the intended basic web application.

    - upload // directory of uploaded files
    - index.php
    - upload.php
    - styles.css
    - script.js

Creating the Index File

To start with, we will create the primary page of the application. This page includes the HTML structure responsible for loading stylesheets, scripts, and the file upload form. It also incorporates the progress bar elements. Kindly save the provided code snippet as index.php.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <meta charset="UTF-8">
  4.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  5.     <title>Upload File with Progress Bar using PHP and JS</title>
  6.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  7.     <link rel="stylesheet" href="styles.css">
  8.     <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
  9.     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  10. </head>
  11.     <main>
  12.         <h3 class="text-center text-light fw-bolder">File Upload with Progress Bar</h3>
  13.         <h4 class="text-center text-light fw-bolder">using PHP and JavaScript</h4>
  14.         <div class="card border-top border-3 border-primary shadow rounded-0 mx-auto">
  15.             <div class="card-body rounded-0">
  16.                 <div class="container-fluid">
  17.                     <!-- Upload Form -->
  18.                     <form action="" id="uploadForm">
  19.                         <div class="mb-3">
  20.                             <label for="file" class="form-label">Browse the file you wish to upload:</label>
  21.                             <input class="form-control form-control-sm" id="file" name="file" type="file" required>
  22.                         </div>
  23.                         <div class="mb-3">
  24.                             <!-- Progress Bar -->
  25.                             <div id="uploadProgressBar">
  26.                                 <div class="bar"></div>
  27.                                 <div class="progress-percentage text-center"></div>
  28.                             </div>
  29.                             <!-- /Progress Bar -->
  30.                         </div>
  31.                         <div class="d-flex w-100 justify-content-center">
  32.                             <button class="btn btn-primary rouded px-5 text-center">Upload</button>
  33.                         </div>
  34.                     </form>
  35.                     <!-- /Upload Form -->
  36.                 </div>
  37.             </div>
  38.         </div>
  39.     </main>
  40.     <script src="./script.js"></script>
  41. </body>
  42. </html>

Creating the Stylesheet File

Now, it's time to create the Cascading Stylesheet (CSS) file responsible for defining the layout and design of various elements. This file will be named styles.css and will be linked within the index.php file.

  1. html, body{
  2.     width: 100%;
  3.     height: 100%;
  4. }
  5. body{
  6.     background-color: #0093E9;
  7.     background-image: linear-gradient(160deg, #0093E9 0%, #80D0C7 100%);
  8.     display: flex;
  9.     justify-content: center;
  10.     align-items: center;
  11. }
  12.  
  13. main{
  14.     width: 600px;
  15. }
  16. @media (max-width: 601px){
  17.     main{
  18.         width: 100%;
  19.     }
  20. }
  21.  
  22. /*
  23. Progress Bar
  24. */
  25. #uploadProgressBar{
  26.     display: none;
  27. }
  28. #uploadProgressBar .bar{
  29.     position: relative;
  30.     width: 100%;
  31.     border: 1px solid #afafaf;
  32.     border-radius: 3px;
  33.     height: 20px;
  34.     box-shadow: 3px 3px 5px #0000004d;
  35.     --progress-width: 0%;
  36.     overflow: hidden;
  37.     margin-bottom: 5px;
  38. }
  39. #uploadProgressBar .bar::before{
  40.     content: "";
  41.     position: absolute;
  42.     height: 100%;
  43.     width: var(--progress-width);
  44.     background: #0093E9;
  45.     transition: all .3s ease-in-out;
  46. }
  47. #uploadProgressBar .bar::after{
  48.     content: "";
  49.     position: absolute;
  50.     height: 100%;
  51.     width: 100%;
  52.     background: linear-gradient(to right, transparent 30%, #ffffff3d 80%, #ffffff1a 100%);
  53.     animation: slide 3s ease-in-out infinite;
  54. }
  55. @keyframes slide {
  56.     0%{
  57.         transform: translateX(-100%);
  58.     }
  59.     100%{
  60.         transform: translateX(100%);
  61.     }
  62.    
  63. }
  64.  
  65. #uploadProgressBar .progress-percentage{
  66.     font-size: 1.3rem;
  67.     font-weight: 700;
  68.     letter-spacing: .5px;
  69.     color: #4d4d4d;
  70. }
  71.    

Creating the Script File

Next, we will create the JavaScript file responsible for managing form submissions and sending requests for file uploads. Additionally, this file includes scripts for monitoring the upload progress and updating the progress bar data. It will be named script.js and will be included in the index.php for execution.

  1. // Form
  2. const form = document.querySelector('#uploadForm')
  3. // Progress Bar
  4. const progressBar = document.getElementById('uploadProgressBar')
  5.  
  6. // Event Listner for Uploading the File
  7. form.addEventListener('submit', uploadFile)
  8.  
  9. function uploadFile(e){
  10.     e.preventDefault()
  11.     // Remove previous upload message
  12.     if(!!form.querySelector('.upload-msg')){
  13.         form.querySelector('.upload-msg').remove()
  14.     }
  15.     // Display Progress Bar
  16.     progressBar.style.setProperty('display', 'block')
  17.     // Disable form's File Input and Button
  18.     form.querySelector('#file').setAttribute('disabled', true)
  19.     form.querySelector('button').setAttribute('disabled', true)
  20.  
  21.     // Start Upload Ajax
  22.     const reqst = new XMLHttpRequest();
  23.     // Event Listener for monitoring the progress
  24.     reqst.upload.addEventListener("progress", uploadProgress);
  25.     // Event Listener when Ajax is completed
  26.     reqst.addEventListener("load", function(e){
  27.         progressBar.after(document.createRange().createContextualFragment(reqst.response))
  28.         form.reset();
  29.         form.querySelector('#file').removeAttribute('disabled')
  30.         form.querySelector('button').removeAttribute('disabled')
  31.     });
  32.     // Event Listener when Ajax throws an error
  33.     reqst.addEventListener("error", function(){
  34.         alert("Uploading file failed due to unknown reason.")
  35.     });
  36.     // Opeing the request
  37.     reqst.open("POST", 'upload.php', true);
  38.     // Creating the formdata
  39.     var formData = new FormData(this);
  40.     formData.append('file', form.querySelector('#file').files[0])
  41.     // Sending the request's data
  42.     reqst.send(formData);
  43.  
  44. }
  45.  
  46. function uploadProgress(e){
  47.     // bytes equevalent to 1 MB in binary
  48.     var bytes = 1048576
  49.     // Getting the current loaded data in MB
  50.     var loaded = (parseFloat(e.loaded) / bytes);
  51.     // Getting the Total data in MB
  52.     var total = (parseFloat(e.total) / bytes);
  53.     // Getting the percentage of the loaded data over the total data
  54.     var percentage = ((loaded / total) * 100).toLocaleString('en-US',{'style':'decimal', maximumFractionDigits:2})
  55.    
  56.     // Update Progress Bar
  57.     progressBar.querySelector('.bar').style.setProperty('--progress-width',percentage + '%');
  58.     progressBar.querySelector('.progress-percentage').innerText = percentage + '%';
  59. }

Creating the File Uploading Script

Lastly, we will create the PHP file that houses the scripts and code responsible for managing the file upload process. This file also includes a script for checking and renaming the uploaded filename if it already exists. It will be named upload.php.

  1. <?php
  2. if(isset($_FILES['file'])){
  3.     $filename = $_FILES['file']['name'];
  4.  
  5.     //Check if directory exists
  6.     if(!is_dir('./upload'))
  7.         mkdir('./upload');
  8.    
  9.     /**
  10.         * Checking if the filename already exists
  11.         */
  12.     $i = 1;
  13.     while(true){
  14.         $i++;
  15.         if(is_file('./upload/'.$filename)){
  16.             $filename = preg_replace("/\./", "_{$i}.", $filename,1);
  17.         }else{
  18.             break;
  19.         }
  20.     }
  21.  
  22.     // Destination of the uploaded file
  23.     $destination = "./upload/".$filename;
  24.     // Uploading the file
  25.     $upload = move_uploaded_file($_FILES['file']['tmp_name'], $destination);
  26.  
  27.     if($upload){
  28.         // IF file upload is successfull
  29.         echo "<div class='alert alert-success rounded-0 upload-msg'>
  30.        File has been uploaded successfully!
  31.        <br>
  32.        <a href='{$destination}' target='_blank'>{$filename}</a>
  33.        </div>";
  34.     }else{
  35.         // If the file upload fails
  36.         echo "<div class='alert alert-danger rounded-0 upload-msg'>Uploading file failed</div>";
  37.     }
  38. }
  39.  
  40. ?>

Note: The upload directory will be automatically created during the file upload process if it is not existing yet.

Below, you'll find images demonstrating the execution of the provided code snippets on my end.

File Upload Form

File Uploading with Progress Bar using PHP and JavaScript Tutorial

Display during File Upload Progress

File Uploading with Progress Bar using PHP and JavaScript Tutorial

Display after Successful File Upload

File Uploading with Progress Bar using PHP and JavaScript Tutorial

DEMO VIDEO

Additionally, I've made the complete compressed source code files available on this website. Feel free to download, modify, or enhance them according to your specific needs or requirements. You'll find the download button located below this article.

And that's it! I hope this PHP and JavaScript Tutorial on File Uploads with Progress Bars contributes to your programming skills and provides you with valuable scripts for your current or future projects.

Explore further on this website for more Free Source Code, Tutorials, and Articles.

Happy Coding =)

Add new comment