General concepts

Last updated on
14 October 2016

The Drupal File API leverages PHP stream wrappers allowing virtually any type of resource to be represented as a normal file. This is a fundamental shift in the way files are managed in comparison to previous versions of Drupal.

What are stream wrappers?

Quite simply, a stream is simple data. This input could be from a normal file, from standard input (STDIN), or even a Drupal node. A wrapper encompasses these streams and determines how to handle a specific protocol. Let's look at a few examples.

http:// This wrapper is included with PHP and allows you to access a URL on the web such as this page.
youtube:// This wrapper is implemented by a Drupal contrib module and tells PHP how to handle a YouTube video.

The handling of these streams is done behind the scenes. Developers building on top of registered stream wrappers don't need to know how to use the YouTube API, or how to implement the HTTP protocol. Those specific details are handled by the wrapper. Of course, the wrapper developer needs to know these protocols, but if you're building on top of an existing wrapper, then you don't need to worry about them!

"Calling" streams

A stream is referenced as scheme://target. The scheme represents the protocol or encoding to be used. For example 'youtube', 'http', 'public', and 'private' are schemes. The target represents the resource desired. This could be a file on the filesystem (public://pictures/me.jpg) or something completely different (youtube://NIfl2o44zb0). It's that simple! As previously noted, the handling of these resources is performed by the wrapper behind the scenes.

Using managed files

The stream reference is stored in the 'uri' property of a managed file object. Use this reference as a file name for most PHP functions. So, given a file ID number $file_id, the following code uses file_get_contents() to read the contents of a managed file into a string:

  $file = file_load($file_id);
  $contents = file_get_contents($file->uri);

[Add link to usage documentation]

Limitations

Once the wrappers are registered you can make normal system calls and PHP will transparently handle them. However, there are just a few shortcomings with PHPs wrapper support, but we've replaced the functionality in Drupal's File API.

[Fill in more information].

Help improve this page

Page status: No known problems

You can: