faqts : Computers : Programming : Languages : PHP : Common Problems : Files

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

23 of 26 people (88%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I parse a directory and delete files based upon the time they were created?

Mar 23rd, 2001 12:43
Ben Udall, Julian Laster, http://www.php.net/manual/en/class.dir.php http://www.php.net/manual/en/function.filectime.php http://www.php.net/manual/en/function.filemtime.php


This will delete any files more than a week old out of /tmp.  It uses 
the the file created time.  If you want to look at the last modified 
time instead, replace filectime with filemtime.
$dir = '/tmp/';
$oldest_date = mktime(0, 0, 0, date('n'), date('j')-7, date('Y'));
$dir_listing = array();
$dir_obj     = dir($dir);
while ($item_name = $dir_obj->read()) {
   $path = $dir.$item_name;
   if (is_file($path) && filectime($path) < $oldest_date)
      unlink($path);
}
$dir_obj->close();