Avatar of bytwo
bytwoFlag for United States of America

asked on 

PHP unlink with loop

I'm really trying to delete files older than 1hr old.  I've found this script through another post and having some trouble with it.

$dir = '/home/directory_location/files';
if ($handle = opendir($dir)) {
  /* This is the correct way to loop over the directory. */
  while (false !== ($file = readdir($handle))) {
    if ($file[0] == '.' || is_dir("$dir/$file")) {
       // ignore hidden files and directories
       continue;
    }
    if ((time() - filemtime($file)) > ($days *86400)) {
      unlink("$dir/$file");
    }
  }
  closedir($handle);
}



1. i have files a few days old and less than 1hr old and the script deleted 100% of the files
2. for each file on the resulting php page, the following error returned:

Warning: filemtime() [function.filemtime]: stat failed for devadminb1a8b72a0d0c1c9f26ef74123b254addgolfrounds.zip in /home/directory_location/maintain.php on line 13

I am assuming it is referring to this line but I am unsure of how to resolve.

    if ((time() - filemtime($file)) > ($days *86400)) {

PHP

Avatar of undefined
Last Comment
bytwo
Avatar of fosiul01
fosiul01
Flag of United Kingdom of Great Britain and Northern Ireland image

How big is the file size ??
Avatar of hernst42
hernst42
Flag of Germany image

The line must be
 if ((time() - filemtime("$dir/$file")) > ($days *86400)) {

1 and 2 have the same cause
time() -0 is allways greater than $days*86400
Avatar of bytwo
bytwo
Flag of United States of America image

ASKER

hernst42--The change worked which is great.  One followup.  If I wanted to only remove files that have a mod time < 1hr from the current server time stamp, how could I modify this?  Is that possible?
ASKER CERTIFIED SOLUTION
Avatar of hernst42
hernst42
Flag of Germany image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of bytwo
bytwo
Flag of United States of America image

ASKER

thank you for your help.  
PHP
PHP

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.

125K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo