PHP Progress Bar Script

print
PHP Progress Bar Script

 

http://w3shaman.com/article/php-progress-bar-script

If you have a long running PHP script that executes many processes, you may need to inform user about the progress of the process when the script is still running and hasn’t finished yet. Using progress bar can be the best option. We can combine the PHP flush() function, Javascript, and also CSS to create a nice progress bar.

There is another method to create the same kind of this progress bar by using Ajax and jQuery. You can read the new article about PHP Ajax Progress Bar.
Here is the technique.

Create at least one div element with a certain width in your HTML document for displaying the progress bar.
Estimate the progress percentage in your PHP script. This number will be used to determine the progress bar’s length.
“Echo” the Javascript for updating the content of div element above with a div that the width percentage is same as the calculated progress. Also give the div a different background color or background image so we can see it.
“Flush” it to the browser.
And this is the code

// Total processes
$total = 10;
// Loop through process
for($i=1; $i<=$total; $i++){
// Calculate the percentation
$percent = intval($i/$total * 100).”%”;

// Javascript for updating the progress bar and information
echo ‘‘;

// This is for the buffer achieve the minimum size in order to flush data
echo str_repeat(‘ ‘,1024*64);

// Send output to browser immediately
flush();

// Sleep one second so we can see the delay
sleep(1);
}
// Tell user that the process is completed
echo ‘‘;
?>

?>
See the live demo here.

SOURCE CODE

The complete source code for my PHP progress bar scripts are available at GitHub : https://github.com/w3shaman/php-progress-bar.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.