2010-06-27 17 views
23

ho scritto questo script PHP per eliminare i vecchi file più vecchi di 24 ore, ma cancellato tutti i file, inclusi quelli più recenti:script php per eliminare i file più vecchi di 24 ore, elimina tutti i file

<?php 
    $path = 'ftmp/'; 
    if ($handle = opendir($path)) { 
    while (false !== ($file = readdir($handle))) { 
     if ((time()-filectime($path.$file)) < 86400) { 
      if (preg_match('/\.pdf$/i', $file)) { 
       unlink($path.$file); 
      } 
     } 
    } 
    } 
?> 
+0

Quale sistema operativo stai utilizzando? Win32 o Unix/Linux? –

+9

non dovrebbe essere> 86400? –

+0

È su un sistema Linux. Vedo il mio errore. Ma perché ha eliminato anche i vecchi file? – ChuckO

risposta

28
(time()-filectime($path.$file)) < 86400 

Se l'ora e l'ora correnti mutato del file sono all'interno 86,4 mila secondo l'uno dall'altro, quindi ...

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

penso che potrebbe essere il problema. Cambialo in> o> = e dovrebbe funzionare correttamente.

8
  1. Vuoi invece >.
  2. A meno che non si esegua Windows, si desidera invece filemtime().
52
<?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); 
    } 
} 

?> 

È inoltre possibile specificare il tipo di file con l'aggiunta di un'estensione dopo la * (jolly) ad es

Per le immagini jpg usare: glob($dir."*.jpg")

Per i file txt usare: glob($dir."*.txt")

Per htm utilizzo file: glob($dir."*.htm")

7
<?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

funzionante 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); 
     } 
    } 
} 
} 
Problemi correlati