简体   繁体   中英

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. The folder path is 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

If you use php script for this, you still need to somehow schedule it to run. So you could instead schedule the deletion itself using cron or scheduled tasks. Here is a good reference for 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.

PHP is really not the tool for scheduled tasks. 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.

is_file($item)

尝试

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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