2010-06-27 104 views
23

我写这个PHP脚本删除超过24个小时, 旧的旧文件,但它删除了所有的文件,包括新的:PHP脚本删除文件超过24个小时,删除所有文件

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

什么操作系统,你使用它呢? Win32或Unix/Linux? – 2010-06-27 02:44:52

+9

不应该是> 86400? – 2010-06-27 02:49:18

+0

它在Linux系统上。 我看到我的错误。但为什么它也删除旧文件? – ChuckO 2010-06-27 02:59:30

回答

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

如果当前时间和文件的更改的时间是86400秒的对方,然后...

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

我认为这可能是你的问题。将其更改为>或> =并且它应该可以正常工作。

8
  1. 您需要改为>
  2. 除非您在Windows上运行,否则您需要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); 
    } 
} 

?> 

您也可以通过*后添加扩展(通配符)如指定文件类型

支持JPG图片使用方法:glob($dir."*.jpg")

对于TXT文件使用:glob($dir."*.txt")

对于HTM文件使用: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

正常工作

$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); 
     } 
    } 
} 
}