Showing progress and avoiding timeout in slow script?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Showing progress and avoiding timeout in slow script?

Post by Apollo »

I'm working on a php script which performs some heavy processing on some huge SQL table. When I just do it all in one big for-loop, the script keeps people wondering if something is happening, and will eventually time out (at least the browser thinks so, even though the php may still be running at the server).

How do I show the progress, e.g. something running from 0% to 100%, and how do I avoid a php timeout?

One possibility would be to process everything in chunks of N items, and letting the script redirect to itself at the end starting at the next block. That way the php will output "converting items 1-100..." and after a few secs, refresh (reload itself) showing "converting items 101-200..." etc.

But is there a better way to do this? It doesn't have to be a fancy page with a graphical progress bar or whatever, just printing "0%...1%...2%...etc" and making sure it doesn't timeout is all I need. I tried using ob_flush() but that didn't seem to do the trick. Or should I combine it with some special headers to avoid timeout or cache issues?

Thanks in advance for any help!
Swede78
Forum Contributor
Posts: 198
Joined: Wed Mar 12, 2003 12:52 pm
Location: IL

Re: Showing progress and avoiding timeout in slow script?

Post by Swede78 »

I did something similar awhile back using the the same idea of reloading the page after a chunk is processed. It works fine, it may not be the most sophisticated method, but it works. Maybe, throw some AJAX in there so it doesn't have to reload the entire page. Although, if the only HTML output is a percentage, that may not be worth the effort.

Also, something you may want to keep in mind... the possibilty of an interruption. My script took hours to run, so I had to add a database to track what accounts had been processed already, just in case client or server side connection was ended.

I'm also curious if there is a more elegant solution to this these days.
Post Reply