stack stack
stack stack

Reputation: 33

PHP Create file and delete it after one hour, one week etc

I want to create a file and can auto delete it after the necessary period. My code is:

 $timeForDelete=$_REQUEST['timeForDelete'];
 $text=$_REQUEST["text"];
 $filename = uniqid(rand(), true) . '.txt';
 if($timeForDelete =="2"){
//how save text to file and  auto delete file after one hour?
 }
 else{
    $f=fopen($filename,'a');
    fwrite($f,$text);  //write to file
 }

if $timeForDelete ==2 : how can I save text to file and auto delete it after one hour? Hope you help solve this problem. Thanks.

Upvotes: 3

Views: 2301

Answers (3)

Mehul Velani
Mehul Velani

Reputation: 761

this code is 100% working

date_default_timezone_set('Asia/Kolkata');

$path = realpath(dirname(__FILE__)) . '\Register.php'; <'Enter Your delete file name'>

$creat_time = date("d-m-Y h:i:s",filemtime($path)); 

$endTime = strtotime("+1 year", strtotime($creat_time));

if(time()>$endTime){
    unlink($path);
}

Upvotes: 0

Peter Chaula
Peter Chaula

Reputation: 3711

Let me try to give an example script that the cron would run.

http://php.net/manual/en/function.filemtime.php

Unfortunately on Linux systems we can't get the file creation date, so fmtime is our best bet. For more info please read the wiki below fmtime's documentation.

Note: This is just a simple example

List all the files in a directory:(/path/to/your/script/yourscript.php)

  //assuming files are stored in /path/to/your/script/myfiles
    $path = realpath(dirname(__FILE__)) . '/myfiles';
    $files = array_diff(scandir($path), ['.', '..']);
    //assuming all your files are in $paths top level

    foreach($files as $file){
        //unix time
        $ctime = fmtime($path . "/$file");
        //basic math
        if(time() > $ctime){
            unlink($path . "/$file");
        }
    }

Your cron job

If you 're running a Unix like OS:

Runs every 5 minutes. You can reconfigure

crontab -e

Add this to the crontab and save:

#invoke the intepreter
*/5 * * * * php /path/to/your/script/yourscript.php

Edit:

Alternatively you can save the upload times of these files in a database to keep track of file creation dates

Upvotes: 3

O Genthe
O Genthe

Reputation: 171

There are a number of ways to do what you are requesting. I would suggest that the quickest way to do this would be:

  1. Creating the file with a name that is uniquely identifiable as needing to be deleted (and based on your question, perhaps a timestamp in the name after which they can be deleted - One hour, one week, etc.)
  2. Write a script that will delete all files containing that unique identifier based on the time they were created.
  3. Set up a cronjob to run the script every 5 minutes and clean up your un-needed files.

Upvotes: 3

Related Questions