PHP

Upload a file showing a progressbar in PHP

In this guide, we'll go step by step on building a script to upload a file in php, using the session upload method, that will show us the completed percentage of the upload while the file is uploading to the server.

You can try the result in the following file input, just make sure to upload a big file so you can see the progress bar in action but no larger than 150 Mb which is the server limit, otherwise the script won't work

The Big Picture.

When uploading a single file, on the background, we can get a session variable that gets updated with the uploaded bytes of that file. While the file uploads, via AJAX (XHR) requests, is possible to get the data of that session variable to calculate the uploaded percentage. On this tutorial we'll use that strategy to build a progessbar that shows the percentage of completion.

Setting up the server, enabling the feature.

On your php.ini file make sure that the session.upload_progress.enabled property value is 1, meaning that's enabled.

The Form.

On the form were the input file is put, is mandatory to include the following input tag:

<input type="hidden" name="<?php echo ini_get('session.upload_progress.name'); ?>" value="test" />

The  value="test"  property is used as a suffix for the session name that will get the data later on, so in this case the session name will be upload_progress_test. 

Also we'll need to include the progessbar html, this html could be placed anywhere on the page, on this example it'll be put inside the form under the input submit tag and will use the classes from the following stylesheet: https://www.w3schools.com/w3css/4/w3.css to give it a proper progressbar look.

<div class="w3-light-grey">
    <div id="progressBar" class="w3-container w3-green w3-center" style="width:0%"><!-- filled by JS--></div>
</div>

The full form code on this example is:

<form id="uploadForm" action="upload.php" method="POST" enctype="multipart/form-data" >
    <h2><?php echo $title ?></h2>
    <input type="hidden" name="<?php echo ini_get('session.upload_progress.name'); ?>" value="test" />
    <input type="file" name="file_input" >
    <input type="submit" value="Send">
    <div class="w3-light-grey">
        <div id="progressBar" class="w3-container w3-green w3-center" style="width:0%"><!-- filled by JS--></div>
    </div>
</form>

 

Alex Perea

Web and software developer, passionate by technology and design. Autodidact and pleased to share any piece of knowledge.