jones jones - 3 months ago 28
PHP Question

Auto delete all files after x-time

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.

Answer

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.