Forcibly download a file by FID

Add a record to Drupals menu system with hook_menu
The path download/% will pass % to page callback hook_force_download.
This page callback function loads the file object and returns the file to the users browser as an attachment.
When the fid arguments is not given or there is no corresponding file object, throw an error and show a 404 page with the error message.

The small amount of code proofs the outstanding possibilities of the Drupal framework once again.

* Implementation of hook_menu
function onlinepdf_menu() {
$items['download'] = array(
'title' => 'Download as ZIP',
'page callback' => 'onlinepdf_force_download',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
return $items;

* Page callback
* Purpose: force a download of a file
* Arguments: fid file identifier
function onlinepdf_force_download($fid = FALSE) {
//load file object from fid argument when fid is given and fid represents a file object
if (if ($fid) && file_load($fid))
$file = file_load($fid);
//extract filename from the file's stream wrapper uri
$filename = basename(drupal_realpath($file->uri));
//send the file to the browser as an attachment
file_transfer($file->uri, array('Content-disposition' => 'attachment; filename='.$filename));
//throw error and return a 404.
watchdog('onlinepdf', 'No file object found. fid argument: %fid', array('%fid' => $fid),
drupal_set_message (t("No file object found. fid argument: $fid"), 'error');
return drupal_not_found();