I am using this code to delete all files in folder
$dir = $_SERVER['DOCUMENT_ROOT'].'/upload/';
$op_dir=opendir($dir);
$x = 5;
$current_time = time();
$difference = $current_time - $x;
while($file=readdir($op_dir ))
{
if($file != "." && $file != ".." ){
var_dump($dir.$file);
unlink ($dir.$file);
}
}
closedir($dir);
But I need to do this action after specific time for example after 6 month all files in the folder should be deleted.I searched more but all codes are related to file creation date not generally specific time.
You can execute the action as cronjob.
Read the following link: Crontab
You also can save a date in a database and consult in top of the script if 6 month have elapsed.
How to calculate starting time for 6 months so we can take directory creation time or save the particular time in a database for calculation .The best option is cronjob for this task
Related
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.
There are a number of ways to do what you are requesting.
I would suggest that the quickest way to do this would be:
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.)
Write a script that will delete all files containing that unique identifier based on the time they were created.
Set up a cronjob to run the script every 5 minutes and clean up your un-needed files.
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
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);
}
I have a php script i run every 5 minutes with Cron from a folder. In the folder there is several images and i add more as time goes.
I was wondering how i can make the php script in the beginning check if NEW files exist after the last time the script was run? If new files exist the script should just go on and if no new files exist then it should not go on. I tried searching around but i cant find anything regarding php.
Anyone that know a quick solution to this problem maybet ?
If the new files are also created with a new timestamp, you can use filemtime() to fetch only files that were created/modified in a specified window of time.
Example:
$files = glob("folder/*.jpg");
$files = array_filter($files, function ($file) { return filemtime($file) >= time() - 5*60; /* modified in the last 5 minutes */ });
if ($files)
{
// there are new files! $files is an array with their names
}
To make sure you won't miss any file, you might want to store the time from last run somewhere, so in case cron delays a second or two and new files were created precisely within that window, you won't lose track of them.
Update for comments:
Now, to store the time from last check, thats up to you to decide how you will do that, you can use database, file, some sort of environment variable etc., but here is an example of how you can do something really simple storing time() in a file:
$last = (int)file_get_contents('folder/timestamp.txt');
file_put_contents('folder/timestamp.txt', time());
$files = glob("folder/*.jpg");
$files = array_filter($files, function ($file) { return filemtime($file) > $last; });
if ($files)
{
// there are new files! $files is an array with their names
}
Just make sure your PHP script can modify folder/timestamp.txt and with this script it will always process new files modified since the last run, no matter how long ago it happened.
Method :
store current time whenever the cron executed in a file or database.
every time when cron starts get the last executed time of the cron from your file or database
count the file which creates after last execution time.
if count greater than 0. process the cron. other wise stop.
You could keep track of the time the script was last run and use filemtime to check if the file was updated or created after your last execution.
http://php.net/manual/en/function.filemtime.php
int filemtime ( string $filename )
Use filemtime() as follows,You will get the added time as date format.
$file_time = date ("F d Y H:i:s.", filemtime($filename);
My data.txt is generated each time when someone is visiting my site. I would like to delete this file on on specific time, let say 1:00AM daily.
I found this script but I'm struggling to update the code :/
Any advice?
<?php
$path = dirname(__FILE__).'/files';
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ((time()-filectime($path.'/'.$file)) < 86400) { // 86400 = 60*60*24
if (preg_match('/\.txt$/i', $file)) {
unlink($path.'/'.$file);
}
}
}
}
?>
The script you posted deletes .txt files in the given folder if they are older than a day but the problem is that this test only happens once - when you run the script.
What you need to do is run this script periodically. If you are running this on Linux you should probably add a cron job that executes this script periodically, say once an hour or once daily.
If you're running this on Windows, there is a task schedule that you could use to accomplish the same thing.
Use task scheduler, such as cron for this purposes. You can remove your file simply via shell command
rm /path/to/data.txt
So there's no need to write a PHP script for that.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Automatically delete files from webserver
I'm logging some XML content to a text file using file_put_contents() in case I need it for debugging.
How do I delete this file after a certain amount of time?
I've got a restrictive .htaccess in the log folder, but I'd rather not leave the info (will have customer's addresses, etc) up on the web for long.
Well, while agreeing with everyone else that you're using the wrong tool for the job, your question is pretty straightforward. So here you go:
write a PHP script that will run from the command line
use a tool like cron or windows scheduled task
invoke the cron every minute/five minutes/etc
Your script would be pretty straightforward:
<?php
$dh = opendir(PATH_TO_DIRECTORY);
while( ($file = readdir($dh)) !== false ) {
if( !preg_match('/^[.]/', $file) ) { // do some sort of filtering on files
$path = PATH_TO_DIRECTORY . DIRECTORY_SEPARATOR . $file;
if( filemtime($path) < strtotime('-1 hour') ) { // check how long it's been around
unlink($path); // remove it
}
}
}
You could also use find if you're working in Linux, but I see that #Rawkode posted that while I was writing this so I'll leave you with his elegant answer for that solution.
You should be using the PHP error_log() function which will respect the php.ini settings.
error_log('Send to PHP error log');
error_log('Sent to my custom log', 3, "/var/tmp/my-errors.log");
You can use a built-in function – filectime – to track the creation date of your log files and then delete those that are old enough to be deleted.
This code searches through the logs directory and deletes logs that are 2 weeks old.
$logs = opendir('logs');
while (($log = readdir($logs)) !== false)
{
if ($log == '.' || $log == '..')
continue;
if (filectime('logs/'.$log) <= time() - 14 * 24 * 60 * 60)
{
unlink('logs/'.$log);
}
}
closedir($logs);
You should be handling your logging better, but to answer your question I'd use the *nix find command.
find /path/to/files* -mtime +5 -delete
This will delete all files that haven't been modified in five days. Adjust to your own needs.
There are two ways you can work it out:
if you write the log to only one file, you can empty the file using something like this:
<?php file_put_contents($logpath, "");
if you generate many files, you can write cleanup function like this:
<?php
$logpath = "/tmp/path/to/log/";
$dirh = opendir($logpath);
while (($file = readdir($dh)) !== false) {
if(in_array($file, array('.', '..'))) continue;
unlink($logpath . $file);
}
closedir($dirh);
You can set up a server Scheduled task (most known as Cron Job under *nix systems) to run on a regular basis and delete the left log files. The task would be to execute a PHP code that will do the job.
See Cron Job Overvieww
Do you know if there is a function in php where it can find all the files in a given directory, that were created the last 1 minute (or in any case at a specified time?).
For example, to select all the txt files that were created the last 10 minutes in a directory..
I hope it's clear what I mean!
Thanx
D.
There is no creation time as such, only modified-time, which will work reliably across operating systems.
The filectime() and filemtime() filesystem functions in PHP will allow
you to check and see when a file has last been changed.
It will return
a timestamp holding the value of the time the file was last altered
You could iterate through the files in the folder, while checking filemtime().
Something like,
foreach (glob("*.txt") as $filename) {
echo filemtime($filename); //echoes timestamp
}
Get all files in directory, loop them through and apply filetime() function to see when they were created/modified. Copy them to another array and do with them what you please.
You can try
$it = new GlobIterator(__DIR__ . "/*.txt");
$last10mis = 600;
$list = array();
foreach ( $it as $file )
(time() - $file->getMTime()) <= $last10mis and $list[] = strval($file);
var_dump($list); // all txt files modified in the last 10mins
There is a function in PHP called filemtime that will return the modified time in a UNIX timestamp.
http://php.net/manual/en/function.filemtime.php
from there, and in the example ont that page, it should be fairly straightforward to apply to your needs.