While working on my next open-source module, Document for Drupal, I had a peculiar situation trying to create sub-directories under Drupal’s files directory (usually located at /sites/default/files).
The module allows users to upload files to Drupal, and the admin interface of the module has a setting to allow administrators to specify the sub-directory under the files directory where the uploaded files should be saved to.
I was creating this sub-directory if it did not exist when the admin settings were saved. I used the following PHP code to create this sub-directory:
{syntaxhighlighter brush: php;fontsize: 100; first-line: 1; } if (!is_dir($full)) {
mkdir($full, 0655, TRUE);
}{/syntaxhighlighter}
Here the variable $full contained the full path of the desired sub-directory to create under the files directory.
This sub-directory got created successfully. However, I always got the following PHP error while trying to upload a file to the newly created sub-directory:
move_uploaded_file() [<a href='function.move-uploaded-file'>function.move-uploaded-file</a>]: Unable to move '/tmp/phpHAAdi3' to 'sites/default/files/doc/Document.pdf' in /home/site/public_html/document/includes/file.inc on line 588.
Stumped, I googled out where I got a reminder about our good old Security Advisory: SA-2006-006, and the SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006 .htaccess directive.
Having developed the Take Control module for Drupal, and blogged about this security directive earlier (see this blog entry), I should have been more vigilant. As it turned out, every sub-directory under Drupal’s files directory must have an .htaccess file with the following directive in it to be able to write to it:
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
Having figured this out, you can manually create a .htaccess file in the new sub-directory with the directive. However, as you might be knowing, you would not be able to write to the files or any sub-directory of it through your Hosting Panel or FTP. That is what Take Control module was created for.
However, a much easier option here was to use the Drupal’s file_check_directory method. This method checks for an existence of a sub-directory inside the files directory and optionally creates it based on the parameters passed.
The method automatically takes care of creating the .htaccess file in the new sub-directory and making it writable.
Recent Comments