18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 11<br />

Stream wrappers<br />

If you've been writing PHP for very long, you have most likely needed to work with<br />

local or remote files at some point. The following PHP code is a common way to read<br />

a file into a variable that you can do something with:<br />

$contents = ";<br />

$handle = fopen("/var/www/htdocs/images/xyzzy.jpg", "rb");<br />

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

$contents .= fread($handle, 8192);<br />

}<br />

fclose($handle);<br />

This is pretty straightforward. You get a handle to a local file using fopen() and<br />

read 8 KB chunks of the file using fread() until feof() indicates that you've<br />

reached the end of the file, at which point you fclose() the handle. The contents<br />

of the file are now in the variable $contents. In addition to local files, you can also<br />

access remote files through fopen() like this:<br />

$handle = fopen("http://drupal.org/files/issues/druplicon_2.png",<br />

"rb");<br />

Data that you can access this way is streamable, meaning you can open it, close it,<br />

or seek to an arbitrary place in it. Stream wrappers are an abstraction layer on top<br />

of streams that tell PHP how to handle specific types of data. When using a stream<br />

wrapper, you refer to the file just like a traditional URL—scheme://target. Often<br />

the target will be the path and filename of a file either located locally or remotely, but<br />

as we will see in our sample code, it can be any data that uniquely identifies the data<br />

you are trying to access.<br />

The above examples use two of PHP's built in stream wrappers. The second uses<br />

the http:// wrapper for accessing websites using the http protocol, and the first<br />

uses the file:// wrapper for accessing files on local storage. file:// is the default<br />

scheme when one is not specified, so in this case simply passing the file's path<br />

works fine.<br />

PHP also allows developers to define their own wrappers for schemes that PHP does<br />

not handle out of the box, and the <strong>Drupal</strong> File API has been built to take advantage<br />

of this. For instance, <strong>Drupal</strong> defines the private scheme to allow <strong>Drupal</strong> developers<br />

to interact with files in <strong>Drupal</strong>'s private file system. Let's look at how this works by<br />

creating a scheme to retrieve images from a remote website.<br />

[ 319 ]

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

Saved successfully!

Ooh no, something went wrong!