Reading/writing files programmatically in Drupal 7

Reading/writing files programmatically in Drupal 7

There are two types of files in Drupal. Managed and Unmanaged.

Managed Files

The file information is stored in file_managed table and files can be linked to nodes and users

Schema of file_managed table

It contains following columns

  • fid
  • uid
  • filename
  • uri
  • filemime
  • filesize
  • status ( whether temporary or permanent)
  • timestamp

Uploading Files

Associating uploaded files with the nodes etc is taken care through table named filed_data_field_file_xxxx where xxxx is the unique name of the particular cck field.

file_default_scheme

It is default scheme of site which could be public or private

Saving a file

Use file_save_data($content,$destination_uri=null,$replace=FILE_EXISTS_RENAME)

If you've a relative/absolute file path - convert it to URI using file_build_uri($path) function.

If you've an URI then convert it to actual path to access using PHP using drupal_realpath($uri)

Attaching Files to Node

Use this sample code to attach a file:

  1. //Attach an empty serialized file
  2. if ($form_state['values']['field_serialized_data'][$form['field_serialized_data']['#language']][0]['fid'] == 0) {
  3. //create the serialized file
  4. $time = time();
  5. $filename = 'public://' . "disavow/$time.sr";
  6. $file_temp = file_save_data(serialize(array()), $filename, FILE_EXISTS_RENAME);
  7.  
  8. if (!$file_temp) {
  9. form_set_error(null, "$filename could not be saved!");
  10. watchdog('ANU_DISAVOW', "$filename could not be saved!", array(), WATCHDOG_ERROR);
  11. return;
  12. }
  13.  
  14. $form_state['values']['field_serialized_data'][$form['field_serialized_data']['#language']][0] = array(
  15. 'fid' => $file_temp->fid,
  16. 'display' => 1,
  17. 'description' => '',
  18. );
  19. }
  20.  

In case in a CCK file field file is not attached then fid will be 0

Accessing Attached Files with Node

Something like this:

  1.  
  2. $fileobj = file_load($form_state['values']['field_serialized_data'][$form['field_serialized_data']['#language']][0]['fid'] );
  3.  
  4. $filepath = drupal_realpath($fileobj->uri);
  5. $file_content_arr = unserialize(file_get_contents($filepath));
  6.  

Generating Temporary File

This api function: drupal_tempnam($directory, $prefix) will generate it. It can accept/return both in URI/filepath format.