34

24 時間以上前の古いファイルを削除するために、この php スクリプトを作成しましたが、新しいファイルを含むすべてのファイルが削除されました。

<?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);
           }
        }
     }
   }
?>
4

6 に答える 6

65
<?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")

于 2012-11-25T19:11:21.947 に答える
34
(time()-filectime($path.$file)) < 86400

現在の時刻とファイルの変更時刻が86400 秒以内にある場合、...

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

それがあなたの問題かもしれないと思います。> または >= に変更すると、正しく機能するはずです。

于 2010-06-27T02:45:03.327 に答える
8
  1. >代わりに欲しい。
  2. Windows で実行している場合を除き、filemtime()代わりに必要です。
于 2010-06-27T02:44:43.667 に答える
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);?>
于 2013-07-01T11:14:29.770 に答える
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);
      }
    }
}
}
于 2016-09-08T04:40:54.310 に答える