PHP CLI Status Indicator

Most times when people write command line scripts they just let the output flow down the screen as a status indicator, or just figure “it’s done when it’s done” But sometimes it would be nice to have a simple clean status indicator, allowing you to monitor progress and gauge time-to-completion. This is actually very easy to accomplish. Simply use
instead of
in your output. Obviously the example below is very simplified, and this can be applied in a much more sophisticated fashion. But it works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<font style="color: darkred">$row_count = get_total_rows_for_processing();</font>
$limit=10000;
<font style="color: darkred">echo "\r\n[  0%]";</font>
for ( $i=0; $i < = $row_count; $i = $i + $limit ) {
  $query="SELECT * FROM table LIMIT {$limit} OFFSET {$i}";
  // do whatever
  <font style="color: darkred">$pct = round((($i+$offset)/$row_count)*100);
  if ( $pct < 10 ) {
    echo "\r[  $pct%]";
  } else {
    if ( $pct < 100 ) {
      echo "\r[ $pct%]";
    } else {
      echo "\r[$pct%]";
    }
  }</font>
}
<font style="color: darkred">echo "\r[100%]\r\n";</font>

Leave a Reply