Last active
February 19, 2019 13:10
-
-
Save zanix/a830b7381219d96c709d to your computer and use it in GitHub Desktop.
PHP CLI Progress Bar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This function will output a progress bar when using PHP in CLI | |
* Call progressBar() for each iteration of a loop | |
* | |
* http://ascii-table.com/ansi-escape-sequences.php | |
*/ | |
function progressBar($current=0, $total=100, $label='', $size=50) { | |
// Don't have to call $current=0 | |
// Bar status is stored between calls | |
static $bars; | |
$new_bar = FALSE; | |
if (!isset($bars[$label])) { | |
// Save bar status for next call | |
$bars[$label] = $current; | |
$new_bar = TRUE; | |
fputs(STDOUT, "$label:\n"); | |
} | |
if ($current == $bars[$label]) { | |
return 0; | |
} | |
// Percentage round off for a more clean, consistent look | |
$perc = round(($current / $total) * 100); | |
// Percent indicator must be four characters, if shorter, add some spaces | |
$perc = str_pad($perc, 4, ' ', STR_PAD_LEFT); | |
$total_size = $size + 7; | |
// if it's not first go, remove the previous bar | |
if (!$new_bar) { | |
for ($place = $total_size; $place > 0; $place--) { | |
// echo a backspace (hex:08) to remove the previous character | |
echo "\x08"; | |
} | |
} | |
// Output the progess bar as it should be | |
for ($place = 0; $place <= $size; $place++) { | |
if ($place <= (($current / $total) * $size)) { | |
// Output purple spaces if we are finished through this point | |
// Colors: Under "Set Graphics Mode" @ http://ascii-table.com/ansi-escape-sequences.php | |
echo "\033[44m \033[0m"; | |
} | |
else { | |
// or dark-grey spaces if not | |
echo "\033[47m \033[0m"; | |
} | |
} | |
// end a bar with a percent indicator | |
echo " $perc%"; | |
if ($current == $total) { | |
// if it's the end, sound bell and add a new line | |
echo "\n"; | |
unset($bars[$label]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment