The correct way to delete all files older than 2 d

2019-01-14 05:38发布

Just curious

        $files = glob(cacheme_directory()."*");
        foreach($files as $file)
        {
            $filemtime=filemtime ($file);
            if (time()-$filemtime>= 172800)
            {
                unlink($file);
            }
        }

I just want to make sure if the code is correct or not. Thanks.

标签: php file caching
8条回答
做个烂人
2楼-- · 2019-01-14 06:08

You should add an is_file() check, because PHP normally lists . and .., as well as sub-directories that could reside in the the directory you're checking.

Also, as this answer suggests, you should replace the pre-calculated seconds with a more expressive notation.

<?php
  $files = glob(cacheme_directory()."*");
  $now   = time();

  foreach ($files as $file) {
    if (is_file($file)) {
      if ($now - filemtime($file) >= 60 * 60 * 24 * 2) { // 2 days
        unlink($file);
      }
    }
  }
?>

Alternatively you could also use the DirectoryIterator, as shown in this answer. In this simple case it doesn't really offer any advantages, but it would be OOP way.

查看更多
Evening l夕情丶
3楼-- · 2019-01-14 06:10

Looks correct to me. I'd just suggest you replace 172800 with 2*24*60*60 for clarity.

查看更多
甜甜的少女心
4楼-- · 2019-01-14 06:11
/** It deletes old files.
 *  @param string $dir Directory
 *  @param int $secs Files older than $secs seconds
 *  @param string $pattern Files matching $pattern
 */
function delete_oldfiles($dir,$secs,$pattern = "/*")
{
    $now = time();
    foreach(glob("$dir$pattern") as $f) {
      if (is_file($f) && ($now - filemtime($f) > $secs)) unlink($f);
    }
}
查看更多
仙女界的扛把子
5楼-- · 2019-01-14 06:12

Another simplier and more modern way, using FilesystemIterator.

I'm using 'logs' directory as an example.

$fileSystemIterator = new FilesystemIterator('logs');
$now = time();
foreach ($fileSystemIterator as $file) {
    if ($now - $file->getCTime() >= 60 * 60 * 24 * 2) // 2 days 
        unlink('logs/'.$file->getFilename());
}

Main advantage is: DirectoryIterator returns virtual directories "." and ".." in a loop. But FilesystemIterator ignores them.

查看更多
欢心
6楼-- · 2019-01-14 06:26

The easiest way is by using DirectoryIterator:

<?php
if (file_exists($folderName)) {
    foreach (new DirectoryIterator($folderName) as $fileInfo) {
        if ($fileInfo->isDot()) {
        continue;
        }
        if ($fileInfo->isFile() && time() - $fileInfo->getCTime() >= 2*24*60*60) {
            unlink($fileInfo->getRealPath());
        }
    }
}
?>
查看更多
Summer. ? 凉城
7楼-- · 2019-01-14 06:31
/* Delete Cache Files Here */
$dir = "cache/"; /** define the directory **/

/*** cycle through all files in the directory ***/
foreach (glob($dir."*") as $file) {
//foreach (glob($dir.'*.*') as $file){

/*** if file is 24 hours (86400 seconds) old then delete it ***/
if (filemtime($file) < time() - 172800) { // 2 days
    unlink($file);
    }
}

Hope it help you.

查看更多
登录 后发表回答