Streams and Network Programming

Jun 19, 2009 Author: Developer

Streams and Network Programming...

An often-forgotten feature of PHP is the streams layer. First introduced in PHP 4.3 by Wez Furlong, the streams layer is most often used without even knowing that it exists: whenever you access a file using fopen(), file(), readfile(), include, require and a multitude of other functions, PHP uses the functionality provided by the streams layer to do the actual “dirty work.”

The streams layer is an abstraction layer for file access. The term “stream” refers to the fact that a number of different resource—like files, but also network connections, compression protocols, and so on—can be considered “streams” of data to be read and/or written either in sequence or at random. There are two types of streams. One group provides access to a certain type of stream resource; the standard PHP distribution includes several built in examples of these:

  • php.*—standard PHP input/output
  • file—standard file access
  • http—access to remote resources via HTTP
  • ftp—access to remote resources via FTP
  • compress.zlib—access to compressed data stream using the zlib compression library.

In addition to these, there are several stream extensions that can be “installed” on top of the existing one to formchains of filters that act cumulatively on a data stream:

  • string.rot13—encodes the data stream using the ROT-13 algorithm
  • string.toupper—converts strings to uppercase
  • string.tolower—converts strings to lowercase
  • string.strip_tags—removes XML tags from a stream
  • convert.*—a family of filters that converts to and from the base64 encoding.
  • mcrypt.*—a family of filters that encrypts and decrypts data according to multiple algorithms
  • zlib.*—a family of filters that compressed and decompresses data using the zlib compression library

While this functionality in itself is very powerful, the real killer feature of streams lies in the ability to implement streams wrappers and filters in your PHP scripts—that is, create your own URI scheme that can access data by any means you desire, or a filter than can be applied to any existing stream access.

views 4734
  1. Add New Comment