Deleting a file after user download it
I am using this for sending file to user
header('Content-type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');
readfile($file);
I want to delete this file after user downloads it, how can i do this?
EDIT: My scenario is like that, when user hits download button, my script will create a temporary zip file and user download it then that temp zip file will be deleted.
EDIT2: OK best way seems running a cron job that will be cleaning temp files once an hour.
EDIT3: I tested my script with unlink
, it works unless user cancel the download. If user cancel the download, zip file stays on the server. So that is enough for now. :)
EDIT4: WOW! connection_aborted()
made the trick !
ignore_user_abort(true);
if (connection_aborted()) {
unlink($f);
}
This one will delete the file even if user cancel the download.
Solution 1:
unlink($filename);
This will delete the file.
It needs to be combined with ignore_user_abort()
Docs so that the unlink
is still executed even the user canceled the download.
ignore_user_abort(true);
...
unlink($f);
Solution 2:
I always use the following solution, using register_shutdown_function:
register_shutdown_function('unlink', $file);