Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are websockets suitable for use with PHP?

I have seen it mentioned in various places around the internet that HTML5 websockets do not work well with PHP, that PHP by it's nature is just suitable for use with them. On the other hand, I see multiple tutorials on using PHP with websockets and Ive noticed some PHP websocket implementation such as http://code.google.com/p/phpwebsocket/

So does anyone have any definitive information on using websockets with PHP. Are they usable with PHP, what are the advantages/disadvantages of using them with PHP as opposed to Java or Python, and why have I read numerous people saying they don't work well together?

like image 778
Jim_CS Avatar asked Jul 09 '12 18:07

Jim_CS


1 Answers

The problem is that WebSockets are designed for long running threads/processes which each maintain multiple event-driven connections, whereas PHP (and it's Apache cohort) was designed around the short-lived single process procedural paradigm (eg. max_execution_time is commonly set to 30 seconds, and the session is single threaded).

That's not to say that it's impossible to write a WebSockets server implementation in PHP. I'm aware of at least one project exists that has done exactly this (but note, even this example gets run from the command line, not through mod_php). But it is likely that the PHP implementation of WebSockets is incompatible with the setup of the cheap/shared hosting where PHP is most commonly used.

So while it's possible to it in PHP, you end up having to run a separate server process (from Apache) anyway, and if you're on the sort of hosting that allows separate server processes then it's easier to write WebSockets code in something which is designed for event-driven programming.

If you're not planning to serve tens of thousands of concurrent duplex connections then it's likely you'd be better off using a combination of AJAX and SSE with your PHP back-end.

like image 76
robertc Avatar answered Oct 16 '22 20:10

robertc