0

I am using PHP gallery that automatically generate photo gallery from directory of images.

http://davidwalsh.name/generate-photo-gallery

I would to modify the script to add the ability to clear all thumbnails inside the thumbs folder after a user defined time interval say 12 or 24 hours.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
appu
  • 127
  • 1
  • 9
  • Simply have read the timestamp of each file or create a temp file that you can use to know when they where created. Then use a loop / function to remove them.. Have the script check when a user views the page, this way it will only fire when the time has passed your set limit.. JSON files are handy in this case as you can also store an array of the files / to delete. – Angry 84 Apr 24 '15 at 08:07

2 Answers2

1

Personally i would not use glob as one wrong mistake in the code and you might end up deleting more than just the specified files.. If you hard code this, you should be safe-ish..

Using a cron job is also another idea, but generally shared hosts dont allow them if this is what your using.. But i would recommend a cron job that runs say every hour and deletes all files with a timestamp older than 12/24 hours..

Example Script Using GLOB

<?php
  $files = glob("thumbnailsfolder/*");
  $now   = time();

  foreach ($files as $file)
    if (is_file($file))
      if ($now - filemtime($file) >= 60*60*24*2) // 2 days
        unlink($file);
?>  

Using DirectoryIterator - My Personal Preference

<?php
    foreach (new DirectoryIterator("thumbnailsfolder") as $fileInfo) {
        if ($fileInfo->isDot()) {
            continue;
        }
        if (time() - $fileInfo->getCTime() >= 1*24*60*60) {
            unlink($fileInfo->getRealPath());
        }
    }
?>  

Examples taken from The correct way to delete all files older than 2 days in PhP

Community
  • 1
  • 1
Angry 84
  • 2,935
  • 1
  • 25
  • 24
0

If you are trying to clear out old files on a regular schedule, it is best to use a cron job.

However, I have done something similiar, where after the user has downloaded or viewed the file, I clear out the directory.

in PHP:

array_map('unlink', glob("tempfiles/*"));

Where the directory location is tempfiles. You could use '*.jpg' to delete just the images.

Sablefoste
  • 4,032
  • 3
  • 37
  • 58
  • I do agree this is the shortest / simple one liner method.. But do please note to the OP that glob should never have a user defined directory/string. But would not allow them to use any form of date/checking control. – Angry 84 Apr 24 '15 at 08:21