Link to home
Start Free TrialLog in
Avatar of oostwijk
oostwijk

asked on

Deleting a file

Hi there,

Can someone help me out ? I wan't to have a script which deletes
files in a certain directory on the server, that are older than let's
say 30 day's. Is there anybody out there who can tell me how I can do this ?

Thanks in advance,
Mike

Avatar of mattrope
mattrope

You can check the file's modification date with the "stat" command, and then determine whether you want to delete it or not.

### Get a list of files in the directory
opendir(DIR, $dir_name);
@files = readdir(DIR);
closedir DIR;

### Check each file and delete if necessary

foreach $filename (@files) {
  $mtime = (stat($filename))[9];

  if ($mtime < time - $TIME_LIMIT) {
     unlink $filename;
  }
}



Obviously this assumes that your CGI script runs with sufficient permissions to list the directory contents and delete files in the directory.  $TIME_LIMIT is how old the file must be to be deleted, in seconds.  You can convert this into days with something like $NUMDAYS * 24 * 60 * 60.

Hope this is what you were looking for.
Avatar of oostwijk

ASKER

Mattrope, I keep getting a [500]Error message. What's wrong with the code ?
If you can help me run the script, i'll give the points to you.

#!/usr/local/bin/perl
$PAD='dummy/dummy/dummy/';
$NUMDAYS=1;
$LIMIET=$NUMDAYS*24*60*60;
### Get a list of files in the directory
opendir(DIR, $PAD);
@files=readdir(DIR);
closedir DIR;

### Check each file and delete if necessary
foreach $filename (@files) {
 $mtime=(stat($filename))[9];

 if ($mtime<time - $LIMIET) {
    unlink $filename;
 }
}
Adjusted points to 155
ASKER CERTIFIED SOLUTION
Avatar of mattrope
mattrope

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Great Job, keep up the good work !!

Thanks