filemtime “warning stat failed for”

落花浮王杯 提交于 2019-11-30 16:27:27

问题


I already read it so many questions and answers about it but I can't still solve my problem...

I'm trying to create a function that deletes all the files with "xml" or "xsl" extension that has been created one day ago. But I'm getting this warning on each file I have:

Warning: filemtime() [function.filemtime]: stat failed for post_1003463425.xml in /home/u188867248/public_html/ampc/library.php on line 44

All the files of this directory have the same structure name "post_ + randomNum + .xml" (example: post_1003463425.xml or post_1456463425.xsl). So I think it's not an encoded problem (like I saw in other questions).

The code of my function is this:

 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); 
    }
}

Thanks for your help :)


回答1:


I think the problem is the realpath of the file. For example your script is working on './', your file is inside the directory './xml'. So better check if the file exists or not, before you get filemtime or unlink it:

  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); 
    }
  }



回答2:


For me the filename involved was appended with a querystring, which this function didn't like.

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

Solution was to chop that off first:

$path = preg_replace('/\?v=[\d]+$/', '', $path);
$fileTime = filemtime($path);



回答3:


Shorter version for those who like short code:

// 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);

    }

}


来源:https://stackoverflow.com/questions/13386082/filemtime-warning-stat-failed-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!