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.
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);
I need to run a check on a folder to see when it was last modified. By this I mean the last time it, or any of the files it contains where last modified.
I have tried two ways so far:
using the stat() function on the folder, and then grabbing mtime
$stat = stat("directory/path/");
echo $stat["mtime"];
using the filemtime() function on the folder
echo (filemtime("directory/path/"));
Both of these methods return the same value, and this value does not change if I update one of the files. I am guessing this is because the folder structure itself does not change, only the content of one of the files.
I guess I could loop through all the files in the directory and check their modification dates, but there are potentially a lot of files and this doesn't seem very efficient.
Can anyone suggest how I might go about getting a last modification time for a folder and its content in an efficient way?
moi.
I suggest that you loop all files using foreach function and use it, i think there's no function for that purpose. Here's very simple example using that loop:
$directory = glob('gfd/*');
foreach ($directory as $file) {
$mdtime = date('d.m.Y H:i:s', filemtime($file));
}
echo "Folder last modified: $mdtime<br />";
Keep in mind that foreach is pretty fast, and if you have files < 3000, i think there's nothing to worried about. If you don't want to use this, you can always save modification date to file or something like that. :)
Subfolder-compatibility:
function rglob($pattern, $flags = 0) {
$files = glob($pattern, $flags);
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
$files = array_merge($files, rglob($dir.'/'.basename($pattern), $flags));
}
return $files;
}
See this question: php glob - scan in subfolders for a file
I want to write one PHP script that will tell me how many folders getting created today( not modified one !! ).
Ex. Suppose if gave the path ( like c:\Data ) so my script must be continuously checking that
give path for if it is new entry of any folder. I have used http://php.net/manual/en/function.date-diff.php. But getting result for modified folders as well.
Quote from #Alin Purcaru:
Use filectime. For Windows it will return the creation time, and for Unix the change time which is the best you can get because on Unix there is no creation time (in most filesystems).
Using a reference file to compare the files age allows you to detect new files whidout using a database.
// Path to the reference file.
// All files newer than this will be treated as new
$referenceFile="c:\Data\ref";
// Location to search for new folders
$dirsLocation="c:\Data\*";
// Get modification date of reference file
if (file_exists($referenceFile))
$referenceTime = fileatime($referenceFile);
else
$referenceTime = 0;
// Compare each directory with the reference file
foreach(glob($dirsLocation, GLOB_ONLYDIR) as $dir) {
if (filectime($dir) > $referenceTime)
echo $dir . " is new!";
}
// Update modification date of the reference file
touch($referenceFile);
Another solution could be to use a database. Any folders that are not in the database are new. This ensures to not catch modified folders.
You might want to try getting your script launched with cron like every one minute and check the difference between directory lists (from before and current I mean), not the dates. It's not a perfect solution, but it will work.
Check directories arays with:
$dirs = array_filter(glob('*'), 'is_dir');
Compare them later with array_diff
I've got a cms, each page stores the time that it was last updated in a database. I've got caching set up in smarty (3.1), but I want to be able to clear the cache and force it to create a new cache file if the page was updated since the last saved cache file, but to do that I need to know when the cached file was created.
Is there a way of getting the timestamp of the cached file?
Thanks
I have recently answered a similar question: Smarty cache site properties in database
<?php
// fill these if you do cache grouping and or have different compiles of the same template
$template = 'foobar.tpl';
$cache_id = null;
$compile_id = null;
$smarty = new Smarty();
$tpl = $smarty->createTemplate($template, $cache_id, $compile_id);
if ($tpl->isCached() && $tpl->cached->timestamp < $yourTimestampFromDB) {
$smarty->clearCache($template, $cache_id, $compile_id);
}
I'm not sure Smarty has anything internal for this. But look at filemtime() and filectime for determining when a file was last modified and changed respectively.
From php.net:
$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last changed: " . date("F d Y H:i:s.", filectime($filename));
}
Difference between modified-time and change-time:
Note: In most Unix filesystems, a file is considered changed when its inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated. See also filemtime() (which is what you want to use when you want to create "Last Modified" footers on web pages) and fileatime().