2

I am trying to make a progress bar that show the status of long PHP scripts. Currently I have a code that works with a given number of preset tasks, but I want it to dynamically take the status of the whole script.

Here is the code:

<html lang="en">
<head>
<title>Progress Bar</title>
</head>
<body>
<!-- Progress bar holder -->
<div id="progress" style="width:500px;border:1px solid #ccc; display: inline-block;"></div> &nbsp; <div style="display: inline-block;" id="somethn"></div> <br>
<!-- Progress information -->
<div id="information" style="width"></div>

<?php
// Total processes
$total = 3000;
// 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("somethn").innerHTML="'.$percent.'";
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();
}
// Tell user that the process is completed
// echo '<script language="javascript">document.getElementById("information").innerHTML="Process completed"</script>';
?>

</body>
</html>

How could such a thing be achived?

Sn0wy
  • 107
  • 2
  • 11
  • 4
    You can't with PHP. PHP won't output to the browser until it is done. You either need a background task, or separate Ajax calls, one to run the function, and one to another function that tracks progress. – Devon Bessemer Apr 27 '15 at 19:38
  • @Devon Ive heard somewhere that Javascript could also be utilized. Is this true? :) – Sn0wy Apr 27 '15 at 19:52
  • not if it is a standalone page being loaded into browser. The browser has no way to know what server is up to – charlietfl Apr 27 '15 at 19:57
  • @user3649604, Yes, AJAX calls would be made through Javascript. You can look into a library like JQuery to simplify things. – Devon Bessemer Apr 27 '15 at 20:13
  • @Devon Yes, it is possible with HTML5 using [server-sent events](http://www.html5rocks.com/en/tutorials/eventsource/basics/) . An example : [Monitor progress of long running php scripts with html5 server sent events](http://www.binarytides.com/monitor-progress-long-running-php-scripts-html5-server-sent-events/) –  Apr 27 '15 at 21:22

1 Answers1

0

That won't work. You had to use AJAX in JS.

These might help you:

Community
  • 1
  • 1
Stefan Wittwer
  • 783
  • 6
  • 16