0

I am doing an excel plugin for my project ,i want to unlink that excel file after the completion of download by the user or cancel by the user in the popup showing for the download.

I have tried the unlink code to getting things done ,but as there is the response ,i am slightly confuse how to make it. Below i have attached some part of code . Any suggestion will highly appreciated.

 $filename = time() . "-ocma-sales-report-" . date("Y-m-d") . ".xlsx"; //'.time() . '-ocma-sales-report-' . date("Y-m-d").'.xls'
                        $objWriter->save("temp_excel/$filename");

                        $filePath = 'temp_excel/' . $filename;
                        $this->response->file($filePath, ['download' => TRUE, 'name' => $filename]);

                        return $this->response;
                        //unlink($filename);

                        exit;
sradha
  • 2,216
  • 1
  • 28
  • 48
  • 1
    I can't tell you how to do it in CakePHP but PHP provides several tools to generate temporary files and get them removed automatically, from the `tmpfile()` function to the `php://temp` stream wrapper. If you handle temp files yourself you'll have to schedule a clean up process because deletion will fail sooner or later. – Álvaro González Sep 16 '16 at 11:23
  • Ok @ÁlvaroGonzález i got it .Thank you – sradha Sep 16 '16 at 11:34

1 Answers1

0

You can use FileSystem/File class for create, modify and delete file. Also for download file you have to use simple php code because $this->response->file($filePath, ['download' => TRUE, 'name' => $filename]); is not allowing to so any operation after executing function.

ob_clean();

$filePath = 'temp_excel/' . $filename;
$size   = filesize($filePath);

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $filename); 
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);
readfile($filePath);

$file = new \Cake\Filesystem\File($filePath);
$file->delete();
exit();
Haresh Vidja
  • 8,340
  • 3
  • 25
  • 42