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
<?php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>Progress Bar</title>
</head>
<body>
<!-- Progress bar holder -->
<div id="progress" style="width:500px;border:1px solid #ccc;"></div>
<!-- Progress information -->
<div id="information" style="width"></div>
<?php
// 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 '<script language="javascript">
document.getElementById("progress").innerHTML="<div style=\"width:'.$percent.';background-color:#ddd;\"> </div>";
document.getElementById("information").innerHTML="'.$i.' row(s) processed.";
</script>';
// 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 '<script language="javascript">document.getElementById("information").innerHTML="Process completed"</script>';
?>
</body>
</html>
?>
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.
Comments
Anonymous (not verified)
Sun, 01/08/2012 - 07:44
Permalink
Perfectly done. I tried to
Perfectly done.
I tried to use it in AJAX with no luck. It processes on background and shows up only after the "Process completed".
Any ideas how to see the process while using in AJAX ?
Thanks )
Anonymous (not verified)
Sun, 01/08/2012 - 07:46
Permalink
Does the comment form work ?
Does the comment form work ?
sam (not verified)
Mon, 04/02/2012 - 19:40
Permalink
query
this script shows "process complited direct?
wt could be the problem?"
Dave (not verified)
Fri, 04/06/2012 - 01:27
Permalink
Simple and works great
This is much simpler than other code that I've seen, and works great. Thanks!
Jeff (not verified)
Mon, 08/27/2012 - 23:43
Permalink
Does not work on demo
It only display the "Process Completed" part once it is done. No progress bar, no percent progression.
Maybe a browser version problem ?
Dhiren (not verified)
Fri, 09/14/2012 - 18:26
Permalink
Nice Work......
Thank you...your script is nice working..
@Jeff --> not a browser version problem but add ob_end_flush(); top of the script.
EX :-
ob_end_flush();
// Total processes
$total = 10;
Thanks !
Anurag Kumar Ch... (not verified)
Tue, 05/07/2013 - 20:23
Permalink
Thanks
You just rock man :-)
Reuben Waitara (not verified)
Thu, 09/20/2012 - 19:04
Permalink
Tight Work
Thank you so much
It worked perfectly for me, very much perfect
Again Thank You
Sam (not verified)
Wed, 12/05/2012 - 06:50
Permalink
Adding this progress bar to phpmailer
Please how can l add this progress bar to my phpmailer code.
if(isset($_POST['action'])== "Coform"){
$action=$_POST['action'];
$message=$_POST['message'];
$emaillist=$_POST['emaillist'];
$from=$_POST['from'];
$replyto=$_POST['replyto'];
$subject=$_POST['subject'];
$realname=$_POST['realname'];
$file_name=$_POST['file'];
$message = urlencode($message);
$message = ereg_replace("%5C%22", "%22", $message);
$message = urldecode($message);
$message = stripslashes($message);
$subject = stripslashes($subject);
if (!$from && !$subject && !$message && !$emaillist){
print "Please complete all fields before sending your
message.";
exit;
}
$allemails = split("\n", $emaillist);
$numemails = count($allemails);
for($x=0; $x<$numemails; $x++){
$to = $allemails[$x];
// 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 '
document.getElementById("progress").innerHTML=" ";
document.getElementById("information").innerHTML="'.$i.' row(s) processed.";
';
// 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);
}
if ($to){
$to = ereg_replace(" ", "", $to);
$message = ereg_replace("&email&", $to, $message);
$subject = ereg_replace("&email&", $to, $subject);
print " $to.......";
flush();
$mail = new PHPMailer();
$mail->IsHTML(true);
$mail->CharSet = "text/html; charset=UTF-8;";
$mail->IsSMTP();
$mail->WordWrap = 80;
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->SMTPDebug = 1;
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "username"; // GMAIL username
$mail->Password = "password"; // GMAIL password
$mail->AddReplyTo($replyto, $realname);
$mail->SetFrom($from, $replyto);
$mail->FromName = $realname; // set from Name
$mail->Subject = $subject;
//////$mail->AddAttachment("test.doc");
$mail->Body = $message;
$mail->AltBody = $message;
$mail->AddAddress("$to"); // to Address
$mail->AddAttachment("files/$attach");
//$mail->AddCC("member@mail.com", "Mr.Member"); //CC
//$mail->AddBCC("member@mail.com", "Mr.Member"); //CC
$mail->set('X-Priority', '1'); //Priority 1 = High, 3 = Normal, 5 = low
$mail->Send();
print "sent";
$mail->ClearAddresses();
flush();
}
}
}
?>
please any help will bw appreciated. thanks
Martin (not verified)
Sun, 03/24/2013 - 02:20
Permalink
Had to reduce the line as it
Had to reduce the line as it was running over bar end
$percent = intval(($i/$total) *100)."%";
To:
$percent = intval(($i/$total) * 71)."%";
Giddy (not verified)
Thu, 05/30/2013 - 18:13
Permalink
Thank you
You just made it very easy. Thank you so much
Vladimir (not verified)
Mon, 06/17/2013 - 23:48
Permalink
Problem with script
I tried to implement script with my php application but had one, for me, big problem. Progress bar immediately fill up, like it have only two steps but my currently loop have 7 iterations and it lasts for about minute to complete. Information bar works like it should but progress making me problem.
Does anyone have idea what could be the problem?
Anonymous (not verified)
Sat, 07/27/2013 - 16:58
Permalink
thanks w3shaman shortest
thanks w3shaman shortest progress bar ever..........................and BIG THANKS to Dhiren for ob_end_flush();
Iconiu (not verified)
Thu, 10/03/2013 - 02:20
Permalink
neat trick, but slow
I don't see you needing a progress bar unless you are processing a ton of data and thus the page is loading slowly. With the progress bar, my page loads in about 2 seconds. I anticipating the wait to go up as more data is collected thus I wanted to put the bar in. However, adding the code makes the processing time increase by a factor of 10. It's nice that I have a progress bar but I have to wait over 20 seconds for it to load now. And that's with removing the sleep command and making it only report every 10,000 rows. Oddly enough, Chrome seem to only start showing the progress at about 80% so you still stare at a blank screen for now 15 seconds before getting any feedback. I love the idea, but it doesn't solve the problem due to it's overhead cost.
vinaybissa (not verified)
Wed, 11/27/2013 - 22:03
Permalink
thanx for bar
thank you sir.....
tomrodgers (not verified)
Tue, 12/17/2013 - 05:05
Permalink
Thanks
Works well in Firefox and IE8. I do see the roughly 10-15 second delay in Chrome as described by Iconiu. Not sure if any can or has sorted this out.
kagiso (not verified)
Wed, 12/18/2013 - 05:13
Permalink
progress bar
this works wonders and its really short unlike others I've seen!!
Bornie21 (not verified)
Thu, 02/06/2014 - 20:26
Permalink
Works Great
Thank you very much. Simple and straight forward.
Mino (not verified)
Fri, 02/07/2014 - 17:46
Permalink
PERFECT!!!
GREAT!!! Easy and work perfectly!!! Congratulations!!!
Step (not verified)
Wed, 04/30/2014 - 04:38
Permalink
doesn't work, help!!
The bar only shows after the page has loaded. My page loads in about 10 seconds, but the bar is only shown at the end, when the loading ends. I've added ob_end_flush(); at the top of the script but it's the same. I'm using php 5.3 .
Pahe (not verified)
Tue, 05/06/2014 - 00:39
Permalink
no work
The demo don't work! If PHP Finish, its send to Browser and all what i see is a 100% compled Progressbar...
spyphone (not verified)
Wed, 05/07/2014 - 15:49
Permalink
How to use ajax
how to use it by ajax? spyphone
fmatamala (not verified)
Mon, 06/09/2014 - 22:52
Permalink
IExplorer slow
Hi,
I implement a function that refresh the status and try the code on IExplorer, Chrome and Firefox but on IExplorer the execution takes more time (about double), that Chrome or Firefox.
The best result is with Chrome because the refresh of text and progress bar is more quick.
Does anyone have idea about IExplorer problem?
fmatamala (not verified)
Mon, 06/09/2014 - 23:27
Permalink
IExplorer slow
I Find the solution,
i replace the:
echo str_repeat(' ',1024*64);
for:
print str_pad('', intval(ini_get('output_buffering')))."\n";
and IExplorer work quickly!
Thaks To:
http://pastebin.com/KSxjC01r
Aario (not verified)
Tue, 07/29/2014 - 17:54
Permalink
Didn't work!
Don't know about happy people saying it works. For me, it just renders:
Process completed
document.getElementById("progress").innerHTML="
[--------------A BIG GRAY BAR HERE----------------------]
"; document.getElementById("information").innerHTML="'.$i.' row(s) processed."; '; // 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 ''; ?> ?>
If anyone know why this happens please take a moment and put a comment hear. Thanks in advance.
Aario (not verified)
Tue, 07/29/2014 - 18:04
Permalink
Got it!
For anyone who has problem executing the script, this is how:
Remove the first line containing:
<?php
And then remove the last line containing:
?>
Then save the file as:
progressbar.php
in linux you must set it as executable by running in terminal:
chmod +x ./progressbar.php
And it should work.
Wizzard (not verified)
Fri, 08/15/2014 - 16:11
Permalink
Does not work, any of the
Does not work, any of the scripts
RamVikas SMaurya (not verified)
Tue, 09/23/2014 - 15:20
Permalink
Computers
Simply Beautiful...
i run it it works perfectly...
Good job....
belaharhebat (not verified)
Tue, 08/04/2015 - 15:52
Permalink
http://belajarhebat.web.id
not bad
Mukhlis Saputro (not verified)
Fri, 03/11/2016 - 14:52
Permalink
Thankyou
Thankyou :) You Save my day
Add new comment