The php Function Stream_Socket_Client
When it comes to socket programming in PHP, most articles talk about the Socket Extension. But there is a more user friendly way to work with sockets: the stream function. In this article, we will cover the php function stream_socket_client and how to use it.
The stream_socket_client() function takes a socket specification as its first argument. The specification is the same as the one that would be passed to a normal fopen(). This means you can use all of the standard file functions, including fgets(), fgetss(), fwrite() and fclose() on it.
The main difference between the stream_socket_client() and the standard fopen() is that the stream_socket_client() returns an object instead of a file. This object has a special method called get_socket_state() that provides the information necessary to communicate with the remote server.
You also have to "Accept" the incoming connection (with stream_socket_accept) before you can start sending data to it. This is a bit of a pain since you have to wait for the incoming data, but it's much easier than having to keep a fread() loop running until something shows up.
Streams come with a variety of wrappers built in by default, see Appendix M for details. Additional, custom wrappers may be added by registering them using the stream_wrapper_register() function. The errno and errstr parameters will contain the actual system level error reported by the connect() call to the wrapper. If the wrapper is able to provide descriptive messages, then message and message_code will be populated with those messages.