Forum Moderators: coopster

Message Too Old, No Replies

Deleting all files in a directory that are older than 1 hour

         

csdude55

8:47 pm on Mar 15, 2018 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm hoping you guys will give this script a second glance to make sure I'm not screwing anything up... I don't really have a sandbox to test on, so this is a spray-and-pray script for me :-O

The plan is for this to run every 24 hours using a cron job, to delete content uploaded by users in a /cache/ directory. I'm starting to get a tad tight on storage, and these are all obsolete after about an hour, anyway.

$dir = '/home/example/www/cache/';

if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ((time() - filectime($file)) > 3600) // 60 sec * 60 min = 3600
unlink($file); // or do I need to use unlink($dir . $file)?
}
}


Or is there a better way to do this with bash scripting (which is not my strength) instead of PHP?

If it matters, the first run will probably delete about 100,000 files, and after that it should be less than 100 a day.

keyplyr

10:46 pm on Mar 15, 2018 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You could do it manually, but if it takes more than an hour, you'd never stop.

csdude55

11:20 pm on Mar 15, 2018 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Haha, right! About 2 years ago I thought that I'd just go in once a month or so and do it manually, but here I am, 2 years later, and haven't touched it since... :-P

TravisDGarrett

10:34 am on Mar 18, 2018 (gmt 0)



I am not a PHP guru, but at first, I would replace

unlink($file);

by

echo "$file\n";

and run the script in command line. Like that you will see exactly if $file is the full path or only the filename .

Also, I think you do not need to call time() for each file, it's not important, but it's silly to fetch the time of the system each time you retrieve one filename. you can put a variable before the loop like:

$now=time();

csdude55

4:08 pm on Mar 19, 2018 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Excellent point, Travis! Thanks :-)