php script to delete files older than 24 hrs, deletes all files

后端 未结 6 1177
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 18:59

I wrote this php script to delete old files older than 24 hrs, but it deleted all the files including newer ones:



        
相关标签:
6条回答
  • 2020-12-02 19:04
    (time()-filectime($path.$file)) < 86400
    

    If the current time and file's changed time are within 86400 seconds of each other, then...

     if (preg_match('/\.pdf$/i', $file)) {
         unlink($path.$file);
     }
    

    I think that may be your problem. Change it to > or >= and it should work correctly.

    0 讨论(0)
  • 2020-12-02 19:06

    $path = '/cache/';
    // 86400 = 1day
    
    if ($handle = opendir($path)) {
         while (false !== ($file = readdir($handle))) {
            if ( (integer)(time()-filemtime($path.$file)) > 86400 && $file !== '.' && $file !== '..') {
                    unlink($path.$file);
                    echo "\r\n the file deleted successfully: " . $path.$file;
            } 
         }
    }

    0 讨论(0)
  • 2020-12-02 19:21

    working fine

    $path = dirname(__FILE__);
    if ($handle = opendir($path)) {
    while (false !== ($file = readdir($handle))) {
    $timer = 300;
    $filetime = filectime($file)+$timer;
    $time = time();
    $count = $time-$filetime;
        if($count >= 0) {
          if (preg_match('/\.png$/i', $file)) {
            unlink($path.'/'.$file);
          }
        }
    }
    }
    
    0 讨论(0)
  • 2020-12-02 19:28
    1. You want > instead.
    2. Unless you're running on Windows, you want filemtime() instead.
    0 讨论(0)
  • 2020-12-02 19:30
    <?php
    
    /** define the directory **/
    $dir = "images/temp/";
    
    /*** cycle through all files in the directory ***/
    foreach (glob($dir."*") as $file) {
    
    /*** if file is 24 hours (86400 seconds) old then delete it ***/
    if(time() - filectime($file) > 86400){
        unlink($file);
        }
    }
    
    ?>
    

    You can also specify file type by adding an extension after the * (wildcard) eg

    For jpg images use: glob($dir."*.jpg")

    For txt files use: glob($dir."*.txt")

    For htm files use: glob($dir."*.htm")

    0 讨论(0)
  • 2020-12-02 19:30
    <?php   
    $dir = getcwd()."/temp/";//dir absolute path
    $interval = strtotime('-24 hours');//files older than 24hours
    
    foreach (glob($dir."*") as $file) 
        //delete if older
        if (filemtime($file) <= $interval ) unlink($file);?>
    
    0 讨论(0)
提交回复
热议问题