PHP script to delete all files in a folder older than X days

I'm looking for a way in PHP to delete all files in a folder that are older than X days.

I have a temp folder and would like to run this script each time a particular PHP page is called so it cleans up old files.
LVL 3
mixartAsked:
Who is Participating?
 
hernst42Connect With a Mentor Commented:
would go like this (untested)
<?php
 
$dir = '/path/to/dir';
if ($handle = opendir($dir)) {
  /* This is the correct way to loop over the directory. */
  while (false !== ($file = readdir($handle))) {
    if ($file[0] == '.' || is_dir("$dir/$file")) {
       // ignore hidden files and directories
       continue;
    }
    if ((time() - filemtime($file)) > ($days *86400)) {
      unlink("$dir/$file");
    }
  }
  closedir($handle);
}

Open in new window

0
 
ray-solomonCommented:
@hernst42
With all respect. Would filectime() be the proper function to use instead of filemtime()?

As one person stated, "in the order of the date they were added". (creation date)
http://www.php.net/manual/en/function.filectime.php#71183

And, filemtime  Gets file modification time

Maybe the asker wants the creation date rather than modification date. Just a suggestion.
0
 
hernst42Commented:
@ray-solomon
> Would filectime() be the proper function to use instead of filemtime()?
no

filectime does not return the file creation time. Unix does not store that information (and AFAIK ntfs also not). filectime returns the file change time:

http://www.php.net/manual/en/function.filectime.php
Gets the inode change time of a file.
In most Unix filesystems, a file is considered changed when its inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated.
Note: Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.

http://www.php.net/manual/en/function.filemtime.php
This function returns the time when the data blocks of a file were being written to, that is, the time when the content of the file was changed.

so in most time filectime and filemtime are the same or filectime >= filemtime. So as conclusion filemtime is nearer to the creationtime as filectime
0
 
ray-solomonCommented:
ah, I see. Thanks for taking the time to clear that up. It was confusing.
:)
0
 
simonoceanCommented:
easier to set-up a cronjob

20 5 * * * find yourfolder/ -type f -name '*.jpg' -mtime +90 -exec rm {} \; >/dev/null 2>&1

// The above will run at 5.20am everyday
It will look in a folder/directory called 'yourfolder' for files with a .jpg extension who's last modified time is 90days or more and then delete any it finds.
0
All Courses

From novice to tech pro — start learning today.