Programmatically Insert Local Files to Managed Files
As numerous posts out there state, this is the way to programmatically add files into Drupal 7's file module tables.
<span style="color: #000000"><span style="color: #0000BB"><?php<br></span><span style="color: #FF8000">// Load the files contents<br></span><span style="color: #0000BB">$image </span><span style="color: #007700">= </span><span style="color: #0000BB">file_get_contents</span><span style="color: #007700">(<</span><span style="color: #0000BB">path to file</span><span style="color: #007700">>);<br><br></span><span style="color: #FF8000">// Returns the new file object<br></span><span style="color: #0000BB">$file </span><span style="color: #007700">= </span><span style="color: #0000BB">file_save_data</span><span style="color: #007700">(</span><span style="color: #0000BB">$image</span><span style="color: #007700">, </span><span style="color: #DD0000">'public://<filename>'</span><span style="color: #007700">, </span><span style="color: #0000BB">FILE_EXISTS_RENAME</span><span style="color: #007700">);<br></span><span style="color: #0000BB">?></span></span>
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.
<span style="color: #000000"><span style="color: #0000BB"><?php<br>$handle </span><span style="color: #007700">= </span><span style="color: #0000BB">fopen</span><span style="color: #007700">(</span><span style="color: #DD0000">'<path to local file>'</span><span style="color: #007700">, </span><span style="color: #DD0000">'r'</span><span style="color: #007700">);<br></span><span style="color: #0000BB">$file </span><span style="color: #007700">= </span><span style="color: #0000BB">file_save_data</span><span style="color: #007700">(</span><span style="color: #0000BB">$handle</span><span style="color: #007700">, </span><span style="color: #DD0000">'public://<filename>'</span><span style="color: #007700">);<br></span><span style="color: #0000BB">fclose</span><span style="color: #007700">(</span><span style="color: #0000BB">$handle</span><span style="color: #007700">);<br></span><span style="color: #0000BB">?></span></span>
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.
Category: Drupal Planet