jump to navigation

A Basic Introduction to PHP Streams April 4, 2013

Posted by Tournas Dimitrios in PHP.

Streams is a feature of PHP that was introduced in PHP 4.3 to unify the methods for working on files , network-sockets , data compression , and other operations which share a common set of functionality . A stream is a resource object which exhibits “stream-able” behavior , in simple words , it can be read from or written to in a linear fashion , and may be able to fseek to an desired location within the stream . A few examples of streams could be :

  • A file on the file-system (server’s hard drive)
  • A HTTP connection to a web-server
  • A TCP , a UDP connection to a server
  • A FTP  connection , a SSH tunnel
  • A ZIP archive

By observing the above list , it is evident that even if these different stream-types share a common functionality (reading  , writing  ) , their implementation couldn’t be the same .  For instance , opening a compressed file (Zip-archive) needs a totally different “mechanism”compared to the “mechanism” used for opening a TCP-connection  . Another example , opening a file on the file-system (server’s hard drive) demands a much simpler “mechanism” than opening a stream socket , which implements “connection-oriented” semantics . Essentially , a “TCP network-stream” requires that the two communicating parties first establish a socket connection (in technical jargon — TCP is a connection oriented protocol) , after which any data passed through that connection will be guaranteed to arrive in the same order in which it was sent . Lastly , other network protocols (UDP)  prefer speed instead of secure-delivery , and utilize a connection-less oriented stream (which has no guarantee for secure delivery of the data) .  As in life , when developing web applications , we have to weigh the  needs and act upon compromises .

PHP has a set of functions that utilizes stream functionality , for instance : fopen() , file() ,  file_get_contents() , file_put_contents() . In fact , you have already been using file streams all the time , completely transparently . PHP also provides a set of predefined “wrapers” ,  which tells those aforementioned stream-functions how to handle specific protocols . There are many wrappers built into PHP by default , custom wrappers may be added either within a PHP script or from an extension using its API . A prime example of a wrapper that uses an extension’s API is the “ssh2://”  wrapper (it needs the SSH2 extension) . Because any variety of wrapper may be added to PHP , there is no limit on what can be done with them .

To access the list of registered wrappers , use the stream_get_wrappers()  function or open a phpinfo  file into your browser and locate the “Registered PHP Streams” section .  Notice : some shared hosts disable specific “wrappers” for security and / or performance .

By default , PHP uses the “file://” wrapper ,  however if you want to work with a different type of stream , you must specify it by pre-fixing your URI with “wrappername://” to indicate the stream wrapper/protocol that you wish to use .  As aforementioned , PHP has a long list of predefined “wrappers” .  Some examples of different wrappers follows :

Before we dig into practical examples , lets first mention an important feature of PHP’s stream-functions :

  •  stream context . The default functionality of each “wrapper” is adequate for basic tasks , we could further tweak each wrapper by specifying a few more options . It is obvious that each “wrapper” has its own set of options , for instance a HTTP protocol could be configured with an extra POST variable and or HEADER data . A FTP protocol , utilizes a totally different mechanism , it doesn’t need (nether supports) Post variables and HEADER data . FTP can be tweaked to overwrite an already existing files on the remote server or to Proxy a FTP request via http proxy server .The context is created with stream_context_create() . Options are set with stream_context_set_option() and parameters with stream_context_set_params() . Finally , here is  a list of supported context options and parameters  , notice : not all wrappers support / need configuration options .

Straight to practical examples :

header('Content-type: text/plain') ;

// A very simple example : Using file_git_contens with the "ftp-wrapper"
$filesize = 4096 ;
if($value = file_get_contents('ftp://abd7d54:2@3#1khsY4@mywebhost.net/public_html/version.php' , NULL , NULL ,  -1 , $filesize ) ) {
echo 'The returned string is : '. $value . '<br>' ;

	} else {
    die('Could not open file.');

// Using the fopen function with an "ftp-wraper"
$ftp_path = 'ftp://abd7d54:2@3#1khsY4@mywebhost.net/public_html/version.php' ;
if ($fh = fopen($ftp_path , 'r')) {
 $value =  fread($fh, filesize($ftp_path));
 echo $value ;
// Closes the file handle
	} else {
    die('Could not open file.');

 This example is from PHP's manual
 Customizing the HTTP-request with "stream-context"
$postdata = http_build_query(
        'var1' => 'some content',
        'var2' => 'doh'

$opts = array('http' =>
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata

$context = stream_context_create($opts);
if ($result = file_get_contents('http://example.com/submit.php', false, $context) ) {
  // do something with $result
  } else {
   die('Could not open file.');


Final  thoughts :

As denoted by this article’s title : “A basic introduction to PHP streams” , this article just “scratched the surface” of a not so known PHP feature . Transparently , PHP uses streams whenever we use one of its  stream functions  . The internal functionality of these functions can be customized by designating another “wrapper” . Further , by passing a “stream context” object to their parameters we can  send extra values to the remote source . Usually the remote source , besides the actual content , it returns also extra “meta-data” which we can catch . Finally , we could attach a filter to the stream which  transforms the data while reading or writing it to the remote source (for instance , compressing data that passes through a stream ) .


1. Divot - April 8, 2013

I like the helpful info you provide in your articles.
I will bookmark your blog and check again here frequently.
I am quite sure I’ll learn many new stuff right here! Best of luck for the next!

2. Vedla - April 17, 2013

This excellent website certainly has all the information and
facts I needed about this subject and didn’t know who to ask.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s