18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Working with Files and Images<br />

File API<br />

In <strong>Drupal</strong> 6, most file handling functionality was provided through a rough core API<br />

combined with contributed modules such as Filefield. <strong>Drupal</strong> 7 provides a more<br />

robust and consistent API that allows developers to interact with files in a standard<br />

set of functions that perform tasks like creating, opening, moving, and deleting files.<br />

In order for files to be associated with nodes and other <strong>Drupal</strong> content, they must<br />

have a record in <strong>Drupal</strong>'s file table. Each record identifies a file with a unique ID<br />

as well as associated metadata like file size and mime-type.<br />

Many File API functions, such as file_copy() and file_move(), take a file object<br />

as one of their arguments. The file object is a PHP standard class containing the<br />

metadata from the files table, and these API functions manage updating the<br />

information in the files table when files are moved or deleted. This is one reason<br />

it is so important to use these API functions for files associated with content—if you<br />

don't, the files table will be inconsistent and your files may not show up properly.<br />

If you need to work with files outside the context of <strong>Drupal</strong> content, there is<br />

a separate set of functions in the File API with unmanaged in their name. For<br />

instance, where file_copy() will update the files table and copy your file,<br />

file_unmanaged_copy() will just copy the file.<br />

For a full list of the functions available in the File API,<br />

refer to the API documentation at:<br />

http://api.drupal.org/api/group/file/7<br />

Here is a simple example of how this works. A common task while building a<br />

<strong>Drupal</strong> site is importing data from another source and turning it into nodes. This<br />

will not only include textual information like the title and body, but also images.<br />

These images may live in a local directory, or they may live out on a website you're<br />

importing from.<br />

Let's look at how we can grab a file from an external site, save it to the default file<br />

system, and attach it to a node we create. For this example, you will be working with<br />

the field image in the article content type.<br />

First we need to get a file and save it:<br />

$image = file_get_contents('http://drupal.org/files/issues/druplicon_<br />

2.png');<br />

$file = file_save_data($image, 'public://druplicon.png',FILE_EXISTS_<br />

REPLACE);<br />

[ 316 ]

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

Saved successfully!

Ooh no, something went wrong!