PHP CLI counter for long running processes
Posted August 29th, 2008 in PHP
I've been doing a reasonable amount of PHP CLI (command line interface) programming recently for getting stuff from log files and converting large numbers of images. Some of these processes can some quite a while to run, sometimes as long as several hours, so it can be useful to know roughly how far through the process it is. This post looks at how to output a counter to the command line from PHP which replaces itself on each iteration.
The important thing with outputting counter information like this is we don't want a big scrolling screen of numbers flying past because it's little messy... this is what would happen if you echo the number out and then follow it with a line break \n
Instead, follow the counter value with a carriage return only \r and each time the value is written out it will replace the line, so you end up with an incrementing value which is always on the same line. This is illustrated in the following example.
for($i = 0; $i < $count; $i++) {
... your code here ...
echo ($i+1), "/$count\r";
}
echo "\n";
This will show e.g. 1/10000, 2/10000, 3/10000 etc always on the same line in your console. At the end we output a final \n newline break so the last line is always displayed.
Running something like this can slow your process down marginally but it's really not going to affect it much if your process is fairly intensive on each loop iteration.
Related posts:
- Check if a PHP script is already running (Tuesday, October 28th 2008)
Recent posts:
- List installed packages with YUM (Tuesday, December 2nd 2008)
- Monthly Roundup - November 2008 (Monday, December 1st 2008)
- Weekly Roundup - December 1st 2008 (Monday, December 1st 2008)
- Installing subversion on CentOS (Sunday, November 30th 2008)
- GoDaddy 99 cent .com domain coupon code (Saturday, November 29th 2008)
- Find the index of a string within a string with Javascript (Friday, November 28th 2008)
Subscribe to RSS Feed / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email and have my posts sent in a daily email.
