Welcome to WebmasterWorld Guest from 34.229.113.106

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

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

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

Senior Member

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

joined:Mar 15, 2013
posts: 1113
votes: 109


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.
10:46 pm on Mar 15, 2018 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member keyplyr is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Sept 26, 2001
posts:12913
votes: 893


You could do it manually, but if it takes more than an hour, you'd never stop.
11:20 pm on Mar 15, 2018 (gmt 0)

Senior Member

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

joined:Mar 15, 2013
posts: 1113
votes: 109


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
10:34 am on Mar 18, 2018 (gmt 0)

Junior Member

joined:Feb 22, 2018
posts:146
votes: 22


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();
4:08 pm on Mar 19, 2018 (gmt 0)

Senior Member

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

joined:Mar 15, 2013
posts: 1113
votes: 109


Excellent point, Travis! Thanks :-)