Drupal 7: Changing file permissions programmatically


ungefähr 0:44 Minuten

One of my recent tasks was a Drupal Commerce Shop that had to export .csv files (generated by Views, triggered by Rules) and save them as unmanaged files in a private directory. The folks these files were addressed to could not fetch them programmatically due to a lack of permission, so I had to alter the standard permissions that Drupal set.

To do that, you can make use of drupal_chmod().

Here's the code I placed in a Rules PHP action.

// Get view for file export
$view = views_get_view('NAME_OF_VIEW');
$display = $view->preview('NAME_OF_DISPLAY');
// saving the file returns the path
// FILE_EXISTS_REPLACE in combination with a 
// static Rules Schedule identifier makes sure you have only 1 file
$file_path = file_unmanaged_save_data($display, 'private://export/NAME_OF_FILE.EXT', FILE_EXISTS_REPLACE);
// set permissions, default: 0664
drupal_chmod($file_path, 0774);

And that's it.

Comments/ Kommentare


What module/s do you use for exporting views? I see there's some trickyness in doing so.


I use views_data_export on that site, exporting lists of current customers and orders in .csv format. I had to patch the module since there has been a BOM issue (see https://www.drupal.org/node/1701018) and another issue with mb_convert_encoding. I did some alterations that are not on drupal.org.

Add new comment/ Neuen Kommentar schreiben

Haben Sie
einen großen