How I delete file after X time from directory?

Discussion in 'PHP' started by chaoscript, Jun 25, 2010.

  1. #1
    Hi,
    I want that my site after X time will delete file from directory.

    Regards.
     
    chaoscript, Jun 25, 2010 IP
  2. raredaredevil

    raredaredevil Greenhorn

    Messages:
    59
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    16
    #2
    I would say use a chronjob if you can , personally I would do it like so:

    1.Create a database entry when the files created/uploaded containing the unixtime stamp of the file upload date.
    2.Have a chronjob running at whatever frequency you require.
    3.Inside the chronjob do this:
    check the result of current unix time stamp - database entry we made in step 1
    If the result of this sum is more than 30 (or however many seconds/minutes to wait before deletion) then delete the file.


    This will not work great if you need extreme accuracy with deletion times but as a chronjob that runs say hourly it would be fine.
     
    raredaredevil, Jun 25, 2010 IP
  3. MyVodaFone

    MyVodaFone Well-Known Member

    Messages:
    1,048
    Likes Received:
    42
    Best Answers:
    10
    Trophy Points:
    195
    #3
    ? Is that delete an actual file like something.php or delete a directory listing entry ?
     
    MyVodaFone, Jun 25, 2010 IP
  4. lukeg32

    lukeg32 Peon

    Messages:
    645
    Likes Received:
    19
    Best Answers:
    1
    Trophy Points:
    0
    #4
    You can do it through a simple shell script;

    E.G the following will delete files that are 7 days old.

    find . -mtime 7 -print | xargs rm
    Code (markup):
    NOTE: Be sure to keep backups of your files. The reason should be obvious.
     
    lukeg32, Jun 25, 2010 IP
  5. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #5
    You could try the following, however you'd need to place this within a global file which would be run regulary...for it to take effect.

    <?php
    
    //time interval for deletion to occur...
    $x = 30;
    
    //timestamp
    $current_time = time();
    
    //the file you wish to delete
    $file_name = 'file.txt';
    
    //timestamp
    $file_creation_time = filemtime($filename);
    
    //extract difference
    $difference = $current_time - $file_creation_time;
    
    //if difference = $x...then delete file
    if ($difference == $x) {
    unlink($file_name);
    }
    ?>
    PHP:
     
    danx10, Jun 28, 2010 IP