2012-06-07 22 views
0

我認爲這個問題被問了很多次,我已經通過並使用了一些來自網絡的代碼。現在我遇到了時間問題。一分鐘後刪除目錄中的文件

讓我先提供代碼:

<?php 
    $pathToDir = getcwd();    

    $pathToFilesDir = $pathToDir . '\files'; 

    $pathToFiles = $pathToFilesDir . '\\'; 

    if ($handle = opendir($pathToFilesDir)) { 

     while (false !== ($file = readdir($handle))) { 

      $filelastmodified = filemtime($file); 

      if ($file != '.' && $file != '..'){    

       if((time() - $filelastmodified) > 60 && is_file($file)){ 

        unlink($pathToFiles . $file); 

       }     
      }     
     } 
     closedir($handle); 
    } 

?> 

這正是我試圖,自動刪除它們1分鐘較舊的文件。僅僅爲了測試的目的,我試了一分鐘。結果是文件不會被刪除。另一方面,我只是刪除了這個時間條件

if((time() - $filelastmodified) > 60 && is_file($file)) 

並運行該腳本,它可以立即刪除文件。

任何一個都可以發現我正在犯的錯誤嗎?

感謝 Raaks

+0

$ filelastmodified的輸出是什麼?和時間的輸出() - $ filelastmodified? – James

+0

喜詹姆斯這是你問filelastmodified1339080970 當前時間1339081082輸出 filelastmodified1336403418 當前時間1339081082 filelastmodified1339076378 當前時間1339081082 filelastmodified1336404883 當前時間1339081082 filelastmodified1336404888 當前時間1339081082 – 125369

+0

這是奇怪的,因爲我使用相同代碼和它的工作原理,這是我的檢查'如果((時間() - @文件時間($ dir。$文件))<$生命期){' – luther

回答

0

這裏的一生我的代碼檢查高速緩存,它工作正常。

if (is_file($dir.$file) && is_readable($dir)) { 
    if ($lifetime) { 
     @clearstatcache(); 
     if ((time() - @filemtime($dir.$file)) < $lifetime) { 
      return file_get_contents($dir.$file); # Return the cache 
     } else { 
      @unlink($dir.$file); # Cache has expired 
     } 
    } else { 
     return file_get_contents($dir.$file); # Return the cache 
    } 
} return null; # Cache not found 
+0

你爲什麼期望'clearstatcache','filemtime'和'unlink'失敗(錯誤抑制運算符)?我的意思是你檢查文件是否存在,是嗎?如果權限設置不好,你不覺得警告會有用嗎? – hakre

+0

@hakre,一個併發進程可能會刪除該文件,所以filemtime/file_get_contents/unlink將會失敗 – strkol