I have a views page that is only accessible by a certain user role. This user role also has permission to "view private files" and to "document: download any files" (coming from File Entity Module). The views page displays a table of all private .pdf files that lie in the private file directory and I would like to add a column to this table, using a Views PHP field (at least for prototyping), that displays the corresponding download link next to the file name. As mentioned above, any user that can view the table also has permission to view private files and to download documents, so this should be doable and not be a security issue.
For now, let's assume I always want to display the download link to a fixed private .pdf file, say with file id $fid=17
. According to Working with files in Drupal,
once configured, files stored in the private directory are inaccessible via a direct link; however, if Drupal constructs a link to the file, the file will be accessible to anyone who can see the link.
What precisely is meant by "if Drupal constructs a link to the file"? I have read many times that file_create_url()
will create a direct link that, if the user has access to view private files, will take the user to the private file. So I tried in my Views PHP field as output code
<?php
$fid = 17;
$file = file_load($fid);
$uri = $file->uri;
$url = file_create_url($uri);
print l(t('Link'), $url);
?>
and the link gets displayed as it should (with reference to mysite.com/system/files/Name_Of_Private_File_17.pdf). But even though the user has permission to view and download private document files, clicking on the link will result in an "Access denied. You are not authorized to access this page."
Can anyone tell me the correct workaround?