title: Websockets for pushing events from server to client in PHP
body: <p>I have a scenario where a webclient has to be updated whenever certain things change on the server. For this I have, on the server side, either</p>
  
  <ul>
  <li>an infinite loop that actively collects changes</li>
  <li>a callback, an eventlistener, hooked into an other system/framework/class with an eventloop</li>
  </ul>
  
  <p>When this mechanism finds a change or receives an event, it needs to pass it on to the webclient over the websocket.</p>
  
  <p>While this is straightforward e.g. in Java where you have the concept of a "running app" thanks to eventloops (threads), this doesn't map that well to PHP. PHP is designed to serve HTTP requests, stateless by nature. When a request comes in, a PHP scripts gets executed, does stuff and renders a response, then dissolves into voidness. </p>
  
  <p>How can I get a serverside PHP process running that does the event listening and provides the means for webclients to open a websocket connection with it? Much like an independently started thread where eventlisteners can subscribe to?</p>
  
  <p>Possible solutions I can think of: </p>
  
  <p><strong>Scenario A: PHP threads (pthreads)</strong></p>
  
  <p>If PHP threads were used, is this how it works?</p>
  
  <ul>
  <li>Webclient A makes a request</li>
  <li>On the server side a new thread is started holding the websocket connection and doing the listening work</li>
  <li>The "normal" response/request thread (the one that spawned the eventlistening thread) ends after sending back a response</li>
  <li>Client and server are now connected. Client A now has its own thread running on the server</li>
  <li>When webclient B makes a request, same happens exclusively for him/her, thus creating a new thread, possibly doing the same job as the first from A</li>
  </ul>
  
  <p><strong>Scenario B: CRON</strong></p>
  
  <p>To simulate the eventloop, a CRON job could be setup to run a PHP script at a certain interval. While that does the job of gathering the events that are of interest to the clients, how do you get hold of the websocket endpoints? As this PHP script runs independently of the Web, how do you join it to the open (?) sockets? Someone has to keep hold of them...</p>
  
  <p><strong>If PHP is a bad match for websockets due to it's "script design", what would be a good alternative?</strong></p>