Drupal - How can I create a download link to a private file?
When I add the field 'File: Download link' to the view it works fine.
The views field handler for the 'File: Download link' has this snippet to check access:
if (!file_entity_access('download', $file)) {
return;
}
and this snippet to construct the uri for the download link:
$uri = file_entity_download_uri($file);
The code for file_entity_download_uri():
function file_entity_download_uri($file) {
$uri = array(
'path' => "file/{$file->fid}/download",
'options' => array(),
);
if (!variable_get('file_entity_allow_insecure_download', FALSE)) {
$uri['options']['query']['token'] = file_entity_get_download_token($file);
}
return $uri;
}
show the download token being added to the options query key of $uri which is returned.
Adding that to the PHP code field:
<?php
$fid = $row->fid;
$file = file_load($fid);
if (file_entity_access('download', $file)) {
$uri = file_entity_download_uri($file);
print l(t('Download'), $uri['path'], array('query' => $uri['options']['query']));
}
?>
results in a download link to the private file.