1

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?

4
  • 1
    Use file transfer and file delete function instead.
    – Shabir A.
    Oct 28, 2015 at 17:45
  • 1
    @Shabir Could you post an example of this or give more info? I don't understand yet Oct 28, 2015 at 17:55
  • 1
    Does the answer solve the issue?
    – Shabir A.
    Oct 28, 2015 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. Oct 28, 2015 at 20:01

1 Answer 1

0

The following code will remove the file after download considering that your file is located in the 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);
  drupal_exit();
}
0

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.