25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

250 ” Streams and Network Programming<br />

are organized in a chain—thus, you can set them up so that the data passes through<br />

multiple filters, sequentially.<br />

You can add a filter to a stream by using stream_filter_prepend() and<br />

stream_filter_append()—which, as you might guess, add a filter to the beginning<br />

and end of the filter chain respectively:<br />

$socket = stream_socket_server("tcp://0.0.0.0:1037");<br />

while ($conn = stream_socket_accept($socket)) {<br />

stream_filter_append($conn, ’string.toupper’);<br />

stream_filter_append($conn, ’zlib.deflate’);<br />

fwrite($conn, "Hello World\n");<br />

fclose($conn);<br />

}<br />

fclose($socket);<br />

In this example, we apply the string.toupper filter to our server stream, which will<br />

convert the data to upper case, followed by the zlib.deflate filter to compress it<br />

whenever we write data to it.<br />

We can then apply the zlib.inflate filter to the client, and complete the implementation<br />

of a compressed data stream between server and client:<br />

$socket = stream_socket_client(’tcp://0.0.0.0:1037’);<br />

stream_filter_append($socket, ’zlib.inflate’);<br />

while (!feof($socket)) {<br />

echo fread($socket, 100);<br />

}<br />

fclose($socket);<br />

If you consider how complex the implementation of a similar compression mechanism<br />

would have normally been, it’s clear that stream filters are a very powerful<br />

feature.<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

Summary<br />

As you can see, streams penetrate to the deepest levels of <strong>PHP</strong>, from general file access<br />

to TCP and UDP sockets. It is even possible to create your own stream protocols<br />

and filters, making this the ultimate interface for sending and receiving data with

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!