Over a discussion about doing WebSocket in PHP on Reddit, I realized that I still had a wrong opinion on this language, considering it as being the scripting language tied to a web server (commonly mod_php, php-fpm or fastcgi). I can also be a scripting language for running tasks, like many web frameworks take advantage of. But you can also write your own server in pure PHP, working at the UDP/TCP level.
Let’s build a web server (aka HTTP server).
#!/usr/bin/env php <?php $socket = stream_socket_server( 'tcp://0.0.0.0:8000', $errno, $errstr ); if (!$socket) { echo "$errstr ($errno)", PHP_EOL; } else { while ($conn = stream_socket_accept($socket, -1)) { $request = ''; while (substr($request, -4) !== "\r\n\r\n") { $request .= fread($conn, 1024); } $response = <<<EOS HTTP/1.1 200 OK Content-Type: text/html Content-Length: 12 Hello World! EOS; fwrite($conn, $response); fclose($conn); } }
This is pretty much it. As PHP isn’t multi-threaded maybe the libevent library can help
but I didn’t manage to install it. Or you could fork it
using the pcntl_fork
way. It actually works, badly but works.
Let’s create a WSGI for PHP. Maybe not.
I’m now wondering who would use this for real production stuff. It’s not close from what exists in the other web servers like Unicorn, Gunicorn, … even if they can leverage threads, native code and existing libraries more easily I guess. Not an expert though.
The code is on Github: pure PHP web servers (non-concurrent and concurrent)