Search code examples
phpircping

How to make my script continuously check a variable?


I'm working on a PHP IRC bot. Currently I'm using a while fgets(... loop to keep it listening for data and responding.

At some point while I was asleep, it actually "pinged out" and stopped getting data, without any sort of error message that I could use to trigger a restart.

I thought of a quick solution, and that's to store the last time the server pinged the bot, and if its more than x seconds, reconnect. This plan works great in theory, except that this ping check is done inside the while fgets loop, so it only checks it when it receives data from the IRC server. As such, if it just stops getting data from the server, it won't compare the ping times, and won't restart.

I can't think of how to get around this.


Solution

  • First of all, use stream_set_timeout() to set the timeout for the (already opened) socket to a value lower than the server ping timeout.

    Then modify the loop condition to: while(fgets(...) || !$done) When you don't get an answer, the fgets will timeout and you might have to suppress the warning for that. But, this way you can send something to the server so it doesn't disconnect you BEFORE you get a ping timeout. Just modify the $done flag and set it to true when you really want to disconnect (however you are doing that).

    Not sure if this works, but it's probably worth a shot.

    Addendum: I was thinking about the exit condition, it would probably be better to manually exit the while (using a break) instead of setting a flag. So you could modify the condition to while(fgets(...) || 1). Otherwise you could be stuck in an endless loop when the server keeps sending content.