Delete a file at shutdown

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
phpwebmaster9
Forum Newbie
Posts: 1
Joined: Mon Feb 03, 2003 1:45 am

Delete a file at shutdown

Post by phpwebmaster9 »

Hello all

I am creating a ZIP file on the fly, storing it in a temporary directory, delivering this file to the user (with readfile) and then finally deleting the temporary ZIP file:

Code: Select all

// pop up 'save as' dialog
if (preg_match("/MSIE/",$_SERVER['HTTP_USER_AGENT'])
		AND !preg_match("/Opera/",$_SERVER['HTTP_USER_AGENT']))
	header("Content-Disposition: filename=".$file_zip);
else
	header("Content-Disposition: attachment;filename=".$file_zip);

header("Content-Type: application/octetstream");
header("Content-Transfer-Encoding: binary");
header("Pragma: no-cache");
header("Expires: 0");
header("Content-Length: ".filesize($file_temp)."");

readfile($file_temp);

// delete temp file
unlink($file_temp);
This works perfectly as long as the file is downloaded successfully. Should the user click on cancel in the browsers “save as” dialog box, the temporary file is not deleted.

I understand that I could implemented some garbage collection, but I was wondering whether it is possible to use PHP’s register_shutdown_function() function to delete the file when the execution of the download script is interrupted.

Or is there some other way to delete a file when the execution of a script is unduely terminated?

Thanks in advance

Sam
User avatar
9902468
Forum Commoner
Posts: 89
Joined: Thu Jun 06, 2002 6:39 am
Location: Europe

Post by 9902468 »

You *could* do a page where you *ask* if user downloads or not? (And delete the package in both cases, ofcourse after the download.) Also if u want it easy just make a script that deletes the whole folder during shutdown. Also you can do timed service deletes using cron...

-9902468
DeGauss
Forum Contributor
Posts: 105
Joined: Tue Oct 22, 2002 9:44 am
Location: Gainesville, FL

Post by DeGauss »

You could store the zip files in your /tmp directory (on unix) or c:\temp (on windows) and set up apache to see those directories as world-readable (unsecure), but at least you'll be sure of garbage collection...
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

is it really necessary to keep the file between two pages?
Why not sending the file within the same request that produced it?
Post Reply