File API overview

Last updated on
14 October 2016

The Drupal 7 File API provides an abstraction layer for accessing virtually any type of resource as a normal file. This is accomplished by leveraging the power of PHP stream wrappers allowing greater collaboration and crossover with a variety of modules. Modules will typically no longer need to know about the filesystem implementation of another in order to interact.

The main File API documentation is derived directly from comments in the code. This Handbook section augments those API docs by providing a tutorial for module authors who wish to interact with the Drupal filesystem, as well as an overview of the system from an administrator's point of view. Note that this Handbook does not cover every feature of the API.

Streamwrapper notation for all files

PHP provides the Streams capability, which allows all files and devices to be accessed with notation like public://something.txt instead of having to figure out where the files directory is, then access it with "sites/default/files/something.txt". Drupal has extended streams to provide the public files directory (by default at sites/default/files) with public:// notation, the private directory (by default sites/default/private) with private:// notation, and temporary files with temporary://somefile.txt. Those three schemes (public, private, and temporary) will be used most often to access files. In general, normal paths will not be used at all when using the Drupal File API.

Since PHP provides streams, though, all the PHP streamwrapper notations can be used by the PHP File functions, including plain paths, ftp://, http://, etc.

Drupal also provides an explicit way for a module to add an additional "scheme" by implementing a hook and a class. The File Example in the Examples Project has a full example implementation of a session:// scheme that writes "files" to the $_SESSION variable.