You want to do WHAT with PHP? Chapter 4

Communication is key to building applications now and for the future. While it is not something that I think that everyone should do, I have not seem many applications that make good use of streams in PHP. Streams can be immensely useful in the right situations, but a lot of developers are not really aware of how streams can be used. In this excerpt from chapter 4 of my book "You want to do WHAT with PHP?" I talk about how you can use streams for fun, and maybe for profit. While I don't think you will end up basing your application around streams it is a really good idea to know how streams work. With that in mind, here is an excerpt from the book.

On some occasions it may be necessary to change stream properties on the fly. To demonstrate this, we will write a simple echo client/server application. The server will listen on a port, echoing whatever it receives and writing back to the socket whatever it had received. Let’s start with just the basics.

What this code is doing is reading the input from the input line, just as it was before, but appending the BZip2 filter when the word “COMPRESS” is typed. When we enable the filter we call stream_filter_append(), take the return value and store it in a sort of global variable. The return value is a resource that describes the socket and filter combination. Later on, when we want to remove the filter, we simply pass the $filter variable to stream_filter_remove() and that filter will flush its contents and be removed. The flushing part is the primary reason why we are using it here. Compression engines work in blocks and as such may not actually send data to the endpoint when you write to it. Removing the filter causes the stream to flush thereby sending all data to the client.

When we run client code we can type these commands, and any other text, simply on the keyboard.

$ php ./enc.client.php
You want to do WHAT with PHP?
COMPRESS
Compression Enabled.
You want to do WHAT with PHP?

Figure 4.15 Client output of enabled compression

Easy enough. But the server side looks quite different.

$ php ./enc.server.php
You want to do WHAT with PHP?
COMPRESS
BZh41AY&SYb@ @D $a 1M211HÉ gHñ%,­#aâ±3)ÂöÏÐ

Figure 4.16 Server output of enabled compression

We see “You want to do WHAT with PHP?” in clear text once, followed by a bunch of binary data. That is about what we would expect to see since after typing in “COMPRESS” we were instructing the client to start compressing the stream.

To make sure that both sides are happy, the next step is to add a read filter on the server side.