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); 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求fpga交通信号灯设计Verilog代码
  • ¥50 adb连接不到手机是怎么回事?
  • ¥20 抓取数据时发生错误: get_mooncake_data() missing 1 required positional argument: 'driver'的问题,怎么改出正确的爬虫代码?
  • ¥15 vs2022无法联网
  • ¥15 TCP的客户端和服务器的互联
  • ¥15 VB.NET操作免驱摄像头
  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人