35

我已经阅读了很多关于它的问题和答案,但我仍然无法解决我的问题......

我正在尝试创建一个函数来删除一天前创建的所有扩展名为“xml”或“xsl”的文件。但是我在我拥有的每个文件上都收到了这个警告:

警告:filemtime() [function.filemtime]: stat failed for post_1003463425.xml in /home/u188867248/public_html/ampc/library.php 在第 44 行

该目录下所有文件的结构名称为“post_ + randomNum + .xml”(例如:post_1003463425.xml 或 post_1456463425.xsl)。所以我认为这不是一个编码问题(就像我在其他问题中看到的那样)。

我的函数代码是这样的:

 function deleteOldFiles(){
    if ($handle = opendir('./xml')) {
        while (false !== ($file = readdir($handle))) { 

            if(preg_match("/^.*\.(xml|xsl)$/i", $file)){

                $filelastmodified = filemtime($file);

                if ( (time()-$filelastmodified ) > 24*3600){
                    unlink($file);
                }
            }
        }
        closedir($handle); 
    }
}

谢谢你的帮助 :)

4

4 回答 4

43

我认为问题是文件的真实路径。例如,您的脚本正在处理“./”,您的文件位于“./xml”目录中。因此,在获取 filemtime 或取消链接之前,最好检查文件是否存在:

  function deleteOldFiles(){
    if ($handle = opendir('./xml')) {
        while (false !== ($file = readdir($handle))) { 

            if(preg_match("/^.*\.(xml|xsl)$/i", $file)){
              $fpath = 'xml/'.$file;
              if (file_exists($fpath)) {
                $filelastmodified = filemtime($fpath);

                if ( (time() - $filelastmodified ) > 24*3600){
                    unlink($fpath);
                }
              }
            }
        }
        closedir($handle); 
    }
  }
于 2012-11-14T19:59:27.953 回答
1

对我来说,所涉及的文件名附加了一个查询字符串,这个函数不喜欢。

$path = 'path/to/my/file.js?v=2'

解决方案是先将其砍掉:

$path = preg_replace('/\?v=[\d]+$/', '', $path);
$fileTime = filemtime($path);
于 2018-06-21T12:55:18.223 回答
1

就我而言,它与路径或文件名无关。如果 filemtime()、fileatime() 或 filectime() 不起作用,请尝试 stat()。

$filedate = date_create(date("Y-m-d", filectime($file)));

变成

$stat = stat($directory.$file);
$filedate = date_create(date("Y-m-d", $stat['ctime']));

这对我有用。

按天数删除文件的完整代码段:

$directory = $_SERVER['DOCUMENT_ROOT'].'/directory/';
$files = array_slice(scandir($directory), 2);
foreach($files as $file)
{
    $extension      = substr($file, -3, 3); 
    if ($extension == 'jpg') // in case you only want specific files deleted
    {
        $stat = stat($directory.$file);
        $filedate = date_create(date("Y-m-d", $stat['ctime']));
        $today = date_create(date("Y-m-d"));
        $days = date_diff($filedate, $today, true);
        if ($days->days > 1) 
        { 
            unlink($directory.$file);
        }
    } 
}
于 2020-06-25T11:49:14.530 回答
0

对于喜欢短代码的人来说,更短的版本:

// usage: deleteOldFiles("./xml", "xml,xsl", 24 * 3600)


function deleteOldFiles($dir, $patterns = "*", int $timeout = 3600) {

    // $dir is directory, $patterns is file types e.g. "txt,xls", $timeout is max age

    foreach (glob($dir."/*"."{{$patterns}}",GLOB_BRACE) as $f) { 

        if (is_writable($f) && filemtime($f) < (time() - $timeout))
            unlink($f);

    }

}
于 2019-07-22T19:47:52.707 回答