Svuotare una cartella dai vecchi files o cartelle di files in php - Parte 2

Come vuotare una cartella dai vecchi files o da cartelle contenente files in php. Può essere utile per svuotare vecchi dump di database.




1)    Definire la cartella da scansionare in automatico
 $files = glob(''.getcwd().'/sql/*'); // Cartella di destinazione

2) Verifica se il file è una cartelal oppure un file singolo

Se è un file:
 if( (is_file($file))  && ($day_diff > 15) ){

Se è una cartella:
 if( (is_dir($file))  && ($day_diff > 15) ){

che rimanda alal funzione  "function deleteDir($dirPath)"




3)  Leggere la data del file in php (nel ciclo)
        $dateFile = date ("Y-m-d H:i:s", filemtime($file));

4) Definire la data massima:
Nell'esempio, si tengono 15 gg ovvero la difefrenza fra la data odierna e 15
        if( (is_file($file))  && ($day_diff > 15) ){



 Script:



/* ---------------
 * Artigiani Del Web - Svuotare una cartella dai vecchi files
o cartelle con files

 * ---------------
 */



 <?php


 function deleteDir($dirPath) {
    if (! is_dir($dirPath)) {
        throw new InvalidArgumentException("$dirPath must be a directory");
    }
    if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
        $dirPath .= '/';
    }
    $files = glob($dirPath . '*', GLOB_MARK);
    foreach ($files as $file) {
        if (is_dir($file)) {
            self::deleteDir($file);
        } else {
            unlink($file);
        }
    }
    rmdir($dirPath);
}



    $files = glob(''.getcwd().'/MYSQL/*'); // Cartella di destinazione
    foreach($files as $file){ // lista files
  
        /* DIFFERENZA DATE */
        $now = date("Y-m-d H:i:s");
        $dateFile = date ("Y-m-d H:i:s", filemtime($file));
      
        $ts1 = strtotime($dateFile);      
        $ts2 = strtotime($now);          
        $seconds_diff = $ts2 - $ts1;      
        $day_diff =  floor($seconds_diff/3600/24);
      
        echo "file: $file <br>";
        echo "now: $now <br>";
        echo "dateFile: $dateFile <br>";
        echo "day_diff: $day_diff <br>";       

      
        /* CANCELLA FILE > 15gg */
        if( (is_file($file))  && ($day_diff > 15) ){
            echo "File vecchio<br />";      
          
            if (chmod($file, 0777)) { echo "<br>CHMOD ok";} else { echo "<br>Errore nel CHMOD";}       
          
            if (unlink($file)) {echo "cartella cancellata<br />";} else { echo '<br>Errore nella cancellazione della cartella';}
        }
      
      
        /* CANCELLA DIRECTORY > 15gg */
        if( (is_dir($file))  && ($day_diff > 15) ){
            echo "CARTELLA vecchia<br />";
          
            if (chmod($file, 0777)) { echo "<br>CHMOD ok";} else { echo "<br>Errore nel CHMOD";}
          
            if (deleteDir($file)) { echo "cartella cancellata<br />";} else { echo '<br>Errore nella cancellazione della cartella'; }

          
        }
  
    }
  
?>   

Commenti