Link to home
Start Free TrialLog in
Avatar of darenceang
darenceang

asked on

PHP - Unlink Timer - Delete files after * mins

Hi!
I have a php page that allows a user to download a unique file. ( based on random number )

The user can download. But i wanted this file to be deleted like 30 mins.
Something like a timer for such files...
EG: User 1 download file qwert.zip at 1200hrs. File to be deleted @ 1230hrs.
User 2 download file zxcvb.zip at 1201hrs. File to be deleted @ 1231 hrs.

Is this workable in php?
I know of the command to delete = unlink()
but don know about the timer...

Please advice.
Cheers!
Darence
Avatar of DigitalTyrant
DigitalTyrant

I have written a similar solution.  I have set the scheduler on the server to run a script, my maintenance script, every 30 mins.  This maintenance script monitors a specific folder, deleting all files that were created more than 24 hours prior.  It's not deadly accurate on the 24 hours, leaving some files almost 24 hours and 30 mins, but it works well to keep my cache clean.
if (filectime($file)+(30*60)<time())  unlink($file);
file change time or you can use filemtime for modify time
In your example, you could setup your script to run more often and be more accurate.  Depending on the size of the zips in question.  Just make sure that the script has enough time to delete all the pending files before it gets called again.  
Avatar of darenceang

ASKER

Hi DigitalTyrant..
May i have a look at the script?

Please advice.
Cheers!
Darence
ASKER CERTIFIED SOLUTION
Avatar of DigitalTyrant
DigitalTyrant

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Digital Tyrant!
Thanks for the advice.
Actually i have a "download" php form that submits the user name
Upon clicking, the form action will go to ./download.php?user=darenceang
It will process and prompt user to download the file.

Am i right to say that your codes go into the ./download.php ? and not another php script?
If i put ur codes in the ./download.php, will it sort of "hang there" while waiting for the time to run out?

Pleae advice.
I wouldn't recommend putting the code in your download.php file.  There are a couple reasons: first, if the script has to run through thousands of files, it would hang on the clients side until it completed, and second, if you only have one visitor an hour, the files would reside on the server longer than the half hour limit it is designed for.

I suggest creating a "purge.php" file that contains the script and then add to the scheduler to run every 5-10 minutes.