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 Jenkins+k8s部署slave节点offline
  • ¥15 微信小游戏反编译后,出现找不到分包的情况
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题