Deleting Files In A Directory Older Than Today Every Week With PHP
A few days ago, before the hacking malarky, I needed a script that I could run via Cron to delete the contents of a folder that were older than a week from a certain day. For example; Let’s say it’s Saturday, I want the script to delete all files older than Saturday… Get what I mean. Right. Let’s continue.
It’s actually fairly simple. Only when you know how. 😆 It’s quite a short script too. I’ll write the script first & then explain it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?php $files = array(); $index = array(); $yesterday = strtotime('yesterday'); if ($handle = opendir('relative/path/to/dir')) { clearstatcache(); while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $files[] = $file; $index[] = filemtime( 'relative/path/to/dir/'.$file ); } } closedir($handle); } asort( $index ); foreach($index as $i => $t) { if($t < $yesterday) { @unlink('relative/path/to/dir/'.$files[$i]); } } ?> |
First we set up two arrays & then the timecode for yesterday using strtotime()
. Next we open the directory, surrounding it with an if just in case. The path is relative from the location of the script, if you are using it as a cron script I recommend placing it in your home directory or somewhere not accessable from the internet.
We next run clearstatcache()
just in case, we don’t want to be trying to delete files that don’t exist. Next we do the file loop. We also use an if to ignore the .
& ..
. We then place every file into the $file
array & then get the modified date from the file into the $index
array. We then close the handle.
Now onto the sorting. We sort the dates using asort()
this keeps key association & sorts the array. Then we run the array through a foreach()
. After the sort we can grab the file that matches the time using the times index (since we used asort()
to keep association). To delete the correct files we check to see if $t
(timecode) is less than yesterday’s timecode. If it is we unlink it (php’s delete function).
If you copy & paste the code please remember to change the file paths. Remember as I said they a relative from the script. Setting the script to run via Cron can be different for different servers but here is the steps I take. This is via SSH:
1 2 |
crontab -e 0 0 * * 6 /full/nix/path/to/php/binary -q /full/nix/path/to/php/script.php |
If it opens in nano then use Ctrl+O to write out (save) then Ctrl+X to exit. Remember these are just for my host your may be different. You can always try there should be any harm, but I’m not responsible for any damage caused if it doesn’t work.
I hope that this is of some use to someone. If really came in handy for me & I always keep in in my little box of tricks, even if you don’t want to delete anything it can be used to sort arrays of files by their date modified & can easily be changed to date created.
13 Comments
Javan Jensen
This is almost what I need. I have no knowledge on how to do this so would appreciate your help. I have several directories which then have folders with the date as the name, examples 0322. I want to be able to go into each directory, cam01, cam02, etc. and delete any folders that are 3 days old. Would like to do this every day so I only have 2 days worth of data in each folder. Can you help me with this?
Thanks
Veneficus Unus
Hey there. This code will kinda work. The main problem is that Unix doesn’t actually have a file creation time only a time last modified or accessed. That is what I use on mine. Anyway the main problem is that when you create a folder or file inside a folder it changes the folders modified date.
I have wrote the following which will empty out all files (since folders can’t be deleted with PHP without first deleting the files) from folders older than 3 days, then delete the mothly named folders older than 3 days & then delete the cam folder if it is older than 3 days. You can stop the deletion of the cam folder if you comment out the 7 lines indicated in the code.
Just change the
$deletion_path
variable to the full *nix path to the folder with the cam folders in. The full *nix path is usually something like/mnt/home/username
or something, and do not add a trailing slash (that’s a slash on the end of the path). Anyway here is the code.Javan Jensen
Thanks,
I will give this a try. Appreciate your help.
Veneficus Unus
No problem. Let me know how it works out & if I can help anymore. 🙂
Todd Horst
Hey, not to bug you but couldn’t you simplify this quite a bit?
eps
Thanks, this worked great.
Veneficus Unus
Yep, you’re right. I just never realized I could have shortened it. The reason my code uses arrays is because I do other things with the file & time info in another script I’m using it in & thought I’d just use that part instead of writing it again.
Thanks for the improvement though. That’s why I love the coding world. 🙂 Although I believe there might be a mistake in your code. You require the setting of the variable
$ret_hr
in the function call & then never use it?Todd Horst
Your right that is a mistake.
$del_date=time()-(2 * 60 * 60);
should be
$del_date=time()-($ret_hr * 60 * 60);
Also I changed
if ($handle = opendir($dir)) {
to
if (is_readable($dir) && $handle = opendir($dir)) {
Thanks for this script though. It was just what i needed.
Veneficus Unus
Np. 🙂
Thanks for the tips in making the code neater too. 😀
Veneficus Unus
Hi,
Creating a cron job is quite simple once you know how. It all depends on your server config. Usually (if there isn’t a way to do it on your host providers website) you log in to your server using shell access (SSH) using a program like Putty.
Once you’re there type crontab -e & the server should automatically create a new cronjob for you. Then to set it up so the script runs every day at 1 in the morning type this in the file:
Once you are done hit Ctrl+o then Ctrl+x that saves & exits.
I hope that helps. If not let me know who you are hosted on & if they give you SSH access (if you don’t know you can always send them an email to ask).
Bridarian Jones
Hi
I need your help and looking at your post I see you know what you are talking about. I want to delete all files in my cache folder every day at 1 in the morning. It is located at /public_html/wp-content/themes/college/cache on my server. I don’t understand how to create a cron job for this. Can you help me please?
Bridarian
Ivor Humphreys
Shouldn’t line 16 in the simpler version have a double & before $t so that:
becomes:
Paul Robinson
Hi Ivor,
Yes, it should. Nice catch there. Will edit it & change it to stop anyone having any trouble with it.
Thanks for the nudge. 😉