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.

Chapter 11<br />

In order to open files from remote locations, PHP must have the allow_<br />

url_fopen setting enabled in your php.ini. For more information see:<br />

http://us2.php.net/manual/en/filesystem.configuration.<br />

php#ini.allow-url-fopen<br />

This is pretty straightforward. Using the PHP function file_get_contents(),<br />

we grab an image of <strong>Drupal</strong>'s mascot, the Druplicon, and save it into the variable<br />

$image. We then save it locally using the <strong>Drupal</strong> API function file_save_data(),<br />

which returns a file object file_save_data(), and takes three arguments. The first<br />

argument is the contents of the file, as a string. file_get_contents() returns a<br />

string, so this works out well.<br />

The second argument specifies the location where the file should be saved. This<br />

destination should be represented as a URI, using one of the system's registered<br />

stream wrappers. We will discuss stream wrappers in more detail later in the<br />

chapter, but for now, just know that you can refer to any of <strong>Drupal</strong>'s file system types<br />

using a custom URI scheme, namely, public://, private://, or temp://. This will<br />

read or write the file into the appropriate file system without the developer needing<br />

to know the details of where the files are physically located. Here we are saving our<br />

file to the public file system.<br />

The third argument specifies what file_save_data() should do when a file already<br />

exists with the same name as the file we're trying to save. There are three constants<br />

defined to indicate the possible actions that <strong>Drupal</strong> can take:<br />

• FILE_EXISTS_REPLACE: The new file should overwrite the existing file.<br />

• FILE_EXISTS_RENAME: Rename the new file by appending an incrementing<br />

number to the new file's name until no collision occurs. For example, if<br />

druplicon.png and druplicon_1.png already existed, then the new file<br />

would be druplicon_2.png.<br />

• FILE_EXISTS_ERROR: Don't do anything and just return FALSE.<br />

The default option is FILE_EXISTS_RENAME but we have specified that the file should<br />

be replaced if it exists.<br />

After the file is saved, a file object is returned. This object contains the fid or file ID,<br />

as well as associated metadata. Now that we have saved the image, we can create a<br />

node and attach the image to it:<br />

$node = new stdClass;<br />

$node->type = 'article';<br />

node_object_prepare($node);<br />

[ 317 ]

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

Saved successfully!

Ooh no, something went wrong!