简体   繁体   English

每隔24小时在PHP中删除一个文件夹中的所有文件

[英]Delete all files of a folder after every 24 hours in PHP

I searched some related questions but unable to understand them. 我搜索了一些相关问题,但无法理解。

I want to delete all the files of folder after every 24 hours but sometimes I get warnings and sometime it works. 我想每隔24小时删除一次文件夹中的所有文件,但有时会收到警告,并且有时它可以工作。 The folder path is c:\\wamp\\www\\Jamil . 文件夹路径为c:\\wamp\\www\\Jamil

Here's the source: 来源:

<?php
$dir = "Jamil"; // directory name

foreach (scandir($dir) as $item) {
    if ($item == '.' || $item == '..')
        continue;

        if((time() - filemtime($item)) >= 30    && is_file($item)){
        unlink($dir.DIRECTORY_SEPARATOR.$item);
        echo "All files deleted";}
    }   
//rmdir($dir);

?>

I copied the code from various sites. 我从各个站点复制了代码。 Can anyone help? 有人可以帮忙吗? I get this warning: 我收到此警告:

Warning: filemtime() [function.filemtime]: stat failed for jamil.html in C:\\wamp\\www\\delete1.php on line 10 警告:filemtime()[function.filemtime]:第10行的C:\\ wamp \\ www \\ delete1.php中jamil.html的统计信息失败

If you use php script for this, you still need to somehow schedule it to run. 如果为此使用php脚本,则仍需要以某种方式安排它的运行。 So you could instead schedule the deletion itself using cron or scheduled tasks. 因此,您可以使用cron或计划的任务来计划删除本身。 Here is a good reference for crontab. 是crontab的良好参考。 If you use Windows write yourself a tiny batch script, go to Control Panel, and you get a nice little wizard guiding you trough task scheduling. 如果您使用Windows,请为自己编写一个小的批处理脚本,请转到“控制面板”,您会看到一个漂亮的小向导,它可以指导您进行任务计划。

PHP is really not the tool for scheduled tasks. PHP确实不是用于计划任务的工具。 It is good if your user needs to do the deletion whenever he/she feels like, but not for scheduled tasks. 如果您的用户需要在需要时执行删除操作(而不是计划任务),则可以这样做。

Try this function; 试试这个功能;

function wipedir($dir) {
        try{  
            if(is_dir($dir)){
                $mydir = opendir($dir);
                while(false !== ($file = readdir($mydir))) {
                    if($file != "." && $file != "..") {
                        chmod($dir.$file, 0777);
                        if(is_dir($dir.$file)) {
                            chdir('.');
                            destroy($dir.$file.'/');
                            rmdir($dir.$file) or DIE("Unable to delete $dir$file");
                        }else{
                            unlink($dir.$file) or DIE("Unable to delete $dir$file");
                        }
                    }
                }
                closedir($mydir);

                return true;
            }else{return true;}
        }catch (Exception $e){return false;} 
    }

So usage would be 所以用法是

$dir = 'Jamil';
wipedir($dir);

This should be placed in a file run by crontab etc at the specified interval. 这应该以指定的间隔放置在crontab等运行的文件中。

is_file($item)

尝试

 if(is_dir($dir.DIRECTORY_SEPARATOR.$item) && $item != ".." && $item != ".")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM