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.
Who is Participating?
hernst42Connect With a Mentor Commented:
would go like this (untested)
$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
    if ((time() - filemtime($file)) > ($days *86400)) {

Open in new window

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)

And, filemtime  Gets file modification time

Maybe the asker wants the creation date rather than modification date. Just a suggestion.
> Would filectime() be the proper function to use instead of filemtime()?

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:
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.
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
ah, I see. Thanks for taking the time to clear that up. It was confusing.
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.
All Courses

From novice to tech pro — start learning today.