Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a file after user download it

Tags:

php

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.

like image 658
Utku Dalmaz Avatar asked Apr 14 '10 23:04

Utku Dalmaz


People also ask

How do I delete files after downloading?

Select the "File Download" trigger event type Next, give this trigger a name, e.g. "Delete Downloaded File". After that, select the "File Download" Event type from the drop-down list. Click Next when you're done.

Does deleting a download get rid of it?

You can delete it, or save it in case you want to reinstall it without having to download it again. You can move or copy it; it won't make any difference where you run it from; it will always install its files where they are supposed to go.

Can you delete downloads after installing?

A. If you have already added the programs to your computer, you can delete the old installation programs piling up in the Downloads folder. Once you have run the installer files, they just sit dormant unless you need to reinstall the program you downloaded.

Can I delete files from Downloads folder?

You may delete each file individually using the Delete key. To remove them all at once, right-click in the downloads section and select Clear Downloads in the drop-down menu.


1 Answers

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); 
like image 138
brettkelly Avatar answered Sep 22 '22 20:09

brettkelly