Programmatically Insert Local Files to Managed Files

Wed 22nd Feb 2012 -- Nick Schuch

As numerous posts out there state, this is the way to programmatically add files into Drupal 7's file module tables.

// Load the files contents
$image = file_get_contents(<path to file>);

// Returns the new file object
$file = file_save_data($image, 'public://<filename>', FILE_EXISTS_RENAME);

However after working on the module CCTV (Currently getting approval for Full Project) I found that this was not enough.

For some background details, CCTV is a module that turns your Drupal site into a IP Camera capture application. Based on the users preference the application can save files up to 1 day in file size (which equates to a very large file). Due to the large file sizes generated by CCTV php runs into memory both max file php configuration and local allocated memory issues. So how do we get around this?

After digging through the file modules documentation I found the following solution.

= fopen('<path to local file>', 'r');
$file = file_save_data($handle, 'public://<filename>');

This opens the file in read only mode and using the file module's function file_save_data it copies the file to the public:// file system. This not only makes your code more efficient, but also allows for bypassing around php's max file size constraints.