Question

How do you auto delete all files under a sub directory after x-time (let say after 24 hours) - without using a cronjob command from server or pl. How can you do this just using PHP code or by just visiting the page without clicking something and the command auto runs.

Was it helpful?

Solution

Response for last comment from my first answer. I'm going to write code sample, so I've created another answer instead of addition one more comment.

To remove files with custom extension you have to implement code:

<?php
  $path = dirname(__FILE__).'/files';
  if ($handle = opendir($path)) {

    while (false !== ($file = readdir($handle))) {
        if ((time()-filectime($path.'/'.$file)) < 86400) {  // 86400 = 60*60*24
          if (preg_match('/\.txt$/i', $file)) {
            unlink($path.'/'.$file);
          }
        }
    }
  }
?>

Comment: 1. This example uses regular expression /\.txt$/i, which means, that only files with extension txt will be removed. '$' sign means, that filename has to be ended with string '.txt'. Flag 'i' indicates, that comparison will be case-insensitive. More about preg_match() function.

Besides you can use strripos() function to search files with certain extension. Here is code snippet:

<?php
  $path = dirname(__FILE__).'/files';
  if ($handle = opendir($path)) {

    while (false !== ($file = readdir($handle))) {
        if ((time()-filectime($path.'/'.$file)) < 86400) {  // 86400 = 60*60*24
          if (strripos($file, '.txt') !== false) {
            unlink($path.'/'.$file);
          }
        }
    }
  }
?>

Comment: This example seems more obvious. Result of strripos() also can be achieved with a combining of two functions: strrpos(strtolower($file), '.txt'), but, IMHO, it's a good rule to use less functions in your code to make it more readable and smaller. Please, read attentively warning on the page of strripos() function(return values block).

One more important notice: if you're using UNIX system, file removing could fail because of file permissions. You can check manual about chmod() function.

Good luck.

OTHER TIPS

You can use PHP core functions filectime() and unlink() to check time of file creation and delete its file/files.

EDIT. Code example:

  if ($handle = opendir('/path/to/files')) {

    while (false !== ($file = readdir($handle))) {
        if (filectime($file)< (time()-86400)) {  // 86400 = 60*60*24
          unlink($file);
        }
    }
  }

Well here we go, the PHP script that deletes the files that is X number of days old.

<?
$days = 1;
$dir = dirname ( __FILE__ );

$nofiles = 0;

    if ($handle = opendir($dir)) {
    while (( $file = readdir($handle)) !== false ) {
        if ( $file == '.' || $file == '..' || is_dir($dir.'/'.$file) ) {
            continue;
        }

        if ((time() - filemtime($dir.'/'.$file)) > ($days *86400)) {
            $nofiles++;
            unlink($dir.'/'.$file);
        }
    }
    closedir($handle);
    echo "Total files deleted: $nofiles \n";
}
?>

Now paste this code and save it as a php file, upload it to the folder from where you want to delete the files. You can see at the beginning of this php code

$days = 1;

that sets the number of days, for example if you set it to 2 then files older than 2 days will be deleted. Basically this is what happens when you run the script, gets the current directory and reads the file entries, skips ‘.’ for current directory and further checks if there are any other directories,

if ( $file == '.' || $file == '..' || is_dir($dir.'/'.$file) ) {
           continue;
}

if the file entry is not a directory then it fetches the file modified time (last modified time) and compares, if it is number of days old

if ((time() - filemtime($dir.'/'.$file)) > ($days *86400)) {
            $nofiles++;
            unlink($dir.'/'.$file);
}

if the condition becomes true then it deletes the file with the help of unlink( ) php function. Finally closes the directory and exits. I have also added a counter to count the number of files being deleted, which will be displayed at the end of deletion process. So place the php file in the directory that needs the file deletion and execute it.

Hopefully that helps :)

Here is another example that uses GLOB and it will delete any file

$files = glob('path/to/your/files/*');

foreach($files as $file) { // iterate files
    // if file creation time is more than 5 minutes
    if ((time() - filectime($file)) > 3600) {  // 86400 = 60*60*24
        unlink($file);
    }
}

or if you want to exclude certain files

$files = preg_grep('#\.txt#', glob('/path/to/your/files/*'), PREG_GREP_INVERT);

After trying to use these examples, I hit a couple of issues:

  1. The comparison operator should be greater than, not less than
  2. filemtime returns the modified time. filectime is the time when a file's inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated, which may lead to unexpected results

I changed the example to use filemtime and fixed the comparison as follows:

<?php
  $path = dirname(__FILE__).'/files';
  if ($handle = opendir($path)) {

    while (false !== ($file = readdir($handle))) {
        if ((time()-filemtime($path.'/'.$file)) > 86400) {  // 86400 = 60*60*24
          if (preg_match('/\.txt$/i', $file)) {
            unlink($path.'/'.$file);
          }
        }
    }
  }
?>

I use shell AT command, it's like a cronjob though

php:

exec("echo rm /somedir/somefile.ext|at now +24 hours");
function deleteCachedData($hours=24)
{
    $files = glob(ROOTDIR.DIRECTORY_SEPARATOR.'tmp'.DIRECTORY_SEPARATOR.'*.txt');
    foreach($files as $file) {
        if(is_file($file) && (time() - filectime($file)) > $hours*3600) {
            unlink($file);
        }
    }

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top