Reputation: 33
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
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
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
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:
Upvotes: 3