Would you like to be notified for every new articles? Please click HERE to subscribe for newsletter.

PHP Progress Bar Script

  • Posted on: 15 December 2011
  • By: admin

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;\">&nbsp;</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

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 )

Does the comment form work ?

this script shows "process complited direct?
wt could be the problem?"

This is much simpler than other code that I've seen, and works great. Thanks!

It only display the "Process Completed" part once it is done. No progress bar, no percent progression.
Maybe a browser version problem ?

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 !

You just rock man :-)

Thank you so much
It worked perfectly for me, very much perfect

Again Thank You

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

Had to reduce the line as it was running over bar end
$percent = intval(($i/$total) *100)."%";
To:
$percent = intval(($i/$total) * 71)."%";

You just made it very easy. Thank you so much

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?

thanks w3shaman shortest progress bar ever..........................and BIG THANKS to Dhiren for ob_end_flush();

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.

thank you sir.....

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.

this works wonders and its really short unlike others I've seen!!

Thank you very much. Simple and straight forward.

GREAT!!! Easy and work perfectly!!! Congratulations!!!

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 .

The demo don't work! If PHP Finish, its send to Browser and all what i see is a 100% compled Progressbar...

how to use it by ajax? spyphone

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?

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

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.

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.

Does not work, any of the scripts

Simply Beautiful...
i run it it works perfectly...
Good job....

Thankyou :) You Save my day

Add new comment

Limited HTML

  • Allowed HTML tags: <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.