php_sockets == headache();

php_sockets == headache();

So, I’ve been “working” with PHP the last few days to create a simple prototype for a web based user interface (for another prototype). Due to the way the system is constructed, the UI must talk to a second component (lets call it X) that does all the actual work with the application server (the web server is on one machine and the application server on another). This is simple enough, or at least that’s what I thought. My plan was to have the UI make the very brief communication with X using local sockets.

I’m no stranger to socket programming, but PHP has taken me out on a not so enjoyable ride that lasted way to long. Problem was that after sending the initial HELLO to X, I was completely unable to read the response from X.The function in question is:

socket_read($socket, $len, $mode)

I checked and re-checked my code, I read through the most popular to the most obscure tutorials Google could provide and I read pretty much all the comments on PHP’s manual pages. All to no avail. I was about to finally give up and look for another way to do this (potentially setting me back a day or two) when I on a hunch added the much familiar \n to the initial HELLO sent to X.

$buf = "some message" . "\n";
socket_write($socket, $buf, strlen($buf));

I started the server/client with no real hope of things working. And just like that, things started to work…

I can’t help but feel that this thing was a really stupid “error”, nowhere could I find anyone saying that this problem could arise and that the solution was this easy. Anyways, if anyone actually reads this blog they’ll know :)

About the Author

My name is, as you can see Robin Mellberg and I live in Luleå which is situated in the northern part of Sweden. When I'm not with my lovely girlfriend I spend my free time playing video games and tabletop games (such as Warhammer and Necromunda).