Minimalistic progress bar for CLI based PHP scripts

I’m doing some CLI scripting here and there and as I’m still on the way to implement it the right way using a framework like wpcli, wpshell or the like for my scripts I sometimes like to put a little progress bar in my scripts to see how things are going and how much longer the script might run. So this is what I do.

<?php

$time1 = time(); 	// set the start time

dosomethingnasty();
function dosomethingnasty() {
	for( $i=0; $i < 300; $i++ ) {
		progress( $i, 300 );
		sleep( 1 );
	}
}


/**
 * Print simple progress bar.
 * 
 * @access public
 * @param int $processed amount of items processed
 * @param int $max maximum amount of items to process
 * @return void
 */
function progress( $processed, $max ) {
	global $time1;
	$progress = round( $processed / ( $max / 100 ), 2);
	$progress_points = floor($progress/2);
	$time_x=time();
	$timediff = $time_x - $time1;
	$estimation = round( ( ( ( 100 / $progress *  $timediff ) - $timediff ) / 60 ), 2 );
	echo str_pad( str_repeat( "#", $progress_points ), 52, " ", STR_PAD_RIGHT) . sprintf( "%.2f", $progress ) . str_pad( "% ( ". sprintf( "%.2f", $estimation ) . " min left )", 27, " ", STR_PAD_RIGHT). "\r" ;
}
About these ads

No comments yet... Be the first to leave a reply!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 185 other followers

%d bloggers like this: