Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I wrote this php script to delete old files older than 24 hrs, but it deleted all the files including newer ones:

<?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);
           }
        }
     }
   }
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
555 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

?>

You can also specify file type by adding an extension after the * (wildcard) eg

For jpg images use: glob($dir."*.jpg")

For txt files use: glob($dir."*.txt")

For htm files use: glob($dir."*.htm")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...