在PHP中删除超过2天的所有文件的正确方法

use*_*951 41 php caching file

只是好奇

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

我只是想确定代码是否正确.谢谢.

bus*_*ens 89

您应该添加一个is_file()检查,因为PHP通常列出...,以及可能驻留在您检查的目录的子目录.

此外,正如这个答案所暗示的那样,您应该用更具表现力的表示法替换预先计算的秒数.

<?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);
      }
    }
  }
?>
Run Code Online (Sandbox Code Playgroud)

或者你也可以使用DirectoryIterator,如这个答案所示.在这个简单的情况下,它并没有真正提供任何优势,但它将是OOP方式.

  • 当我与Python进行短暂的联络时,我写回了这个答案.已添加括号.;) (4认同)
  • 像魅力一样,但为什么你们总是排除括号{}我喜欢它们:D我离不开它们.代码是裸的 (3认同)

小智 52

最简单的方法是使用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());
        }
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用,但如果你只是在while循环之前计算time()和2*24*60*60并在循环中使用变量,那么它会更快. (5认同)
  • 是否需要检查“isDot()”?`isFile()` 检查是否足够了? (2认同)

Mak*_*m.T 10

另一种更简单,更现代的方法,使用FilesystemIterator.

我使用'logs'目录作为例子.

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

主要优点是:DirectoryIterator返回虚拟目录"." 和".."在循环中.但FilesystemIterator会忽略它们.


小智 8

我认为这更整洁,更易于阅读和修改。

$expire = strtotime('-7 DAYS');

$files = glob($path . '/*');

foreach ($files as $file) {

    // Skip anything that is not a file
    if (!is_file($file)) {
        continue;
    }

    // Skip any files that have not expired
    if (filemtime($file) > $expire) {
        continue;
    }

    unlink($file);
}
Run Code Online (Sandbox Code Playgroud)


Lac*_*hit 6

/* 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

希望对您有帮助。

我在 2023 年更新了此代码,请查看: https: //www.arnlweb.com/forums/server-management/efficient-php-code-for-deleting-files-delete-all-files-older-than-2 -正确的日子/