dtlygweb2017 2013-06-09 17:14
浏览 27
已采纳

删除旧文件的功能会引发“stat failed”错误

I am trying to use this simple bit of code to iterate through the "export" folder and delete files older than 24 hours:

if ($handle = opendir("/home/username/public_html/en/graphs/export")) {

    while (false !== ($file = readdir($handle))) { 
        $filelastmodified = filemtime($file);

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

    }

    closedir($handle); 
}

Some notes:

1) I do realize there are similar questions, but the solutions suggested there don't seem to work for me. 2) The absolute path to the directory is correct (tested) 3) The directory has 777 permissions. The files in it don't, but I tested with some files with 777 permissions and the same errors happened. So it doesn't seem to be a permission issue. 4) The file that contains this code is in a different directory (it's a cron job, I like to keep them together in a separate directory)

This is the error that appears (for each file in the directory):

Warning: filemtime() [function.filemtime]: stat failed for countries_rjRp9.png in /home/username/public_html/path-to-crons/crons/exports.php on line 12

Warning: unlink(countries_rjRp9.png) [function.unlink]: No such file or directory in /home/username/public_html/path-to-crons/crons/exports.php on line 16

In this example, countries_rjRp9.png is one of the files that should be unlinked from the export directory.

What's going on here?

  • 写回答

1条回答 默认 最新

  • douyi1197 2013-06-09 17:17
    关注

    You should specify the full path to unlink the file. In your loop, $file will be countries_rjRp9.png and you're trying to unlink it from the working directory, which is, the directory in which all of your cronjobs reside.

    You state that the absolute path to your files is correct, but you forgot to use the absolute path once you're in your loop. You're only using an absolute path in your opendir() call, nowhere else.

    Try doing something like this:

    if ($handle = opendir("/home/username/public_html/en/graphs/export")) {
    
        while (false !== ($file = readdir($handle))) {
            // Take the filename and add its full path
            $file = "/home/username/public_html/en/graphs/export/" . $file;
            $filelastmodified = filemtime($file);
    
            if((time() - $filelastmodified) > 24*3600)
            {
               unlink($file);
            }
    
        }
    
        closedir($handle); 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭