In a custom module I create a file and then use drupal_goto to download it. How can I delete the file after it is downloaded? Placing a file_unmanaged_delete after the drupal_goto doesn't get executed, and hook_file_download happens before the download for permissions checks and such. So I'm not sure how to do this. Do I have to resort to cleaning up files in a folder with cron somehow?

  • 1
    Use file transfer and file delete function instead. – Shabir A. Oct 28 '15 at 17:45
  • 1
    @Shabir Could you post an example of this or give more info? I don't understand yet – digitgopher Oct 28 '15 at 17:55
  • 1
    Does the answer solve the issue? – Shabir A. Oct 28 '15 at 19:51
  • 1
    @Shabir I did not get it to work. I am also uncomfortable using those low-level php functions, and drupal_add_http_header just doesn't seem like a good solution. As a workaround to not having a post-download hook or another callback somewhere, I've created these files in a special directory that I just wipe with hook_cron. – digitgopher Oct 28 '15 at 20:01

The following code will remove the file after download considering that your file is located in tmp directory.

$filename = 'foobar.xls';
$temp_path = realpath(file_directory_temp()) . '/';
if (file_exists($temp_path . $filename)) {
  // Serve file download.
  drupal_add_http_header('Pragma', 'public');
  drupal_add_http_header('Expires', '0');
  drupal_add_http_header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
  drupal_add_http_header('Content-Type', 'application/vnd.ms-excel');
  drupal_add_http_header('Content-Disposition', 'attachment; filename=' . basename($temp_path . $filename) . ';');
  drupal_add_http_header('Content-Transfer-Encoding', 'binary');
  drupal_add_http_header('Content-Length', filesize($temp_path . $filename));
  readfile($temp_path . $filename);
  unlink($temp_path . $filename);

You can visit the following link for details http://kahthong.com/2012/08/simple-example-how-use-drupal-serve-file-downloads


  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Shawn Conn Oct 28 '15 at 19:42
  • 1
    I have edited my answer. – Shabir A. Oct 28 '15 at 19:48
// Generate pdf card.
$file_path = $crm_card->generatePdfCard();
$filename = basename($file_path);
$headers = [
  'Content-Type' => 'application/octet-stream',
  'Content-Disposition' => 'attachment; filename="' . $filename . '"',
  'Content-Length' => filesize($file_path),

$binary_file_response = new BinaryFileResponse($file_path, 200, $headers);

return $binary_file_response;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.