Check for new files in a folder - php

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);

Related

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.
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);
}

PHP Script for Monitoring Folder Creation

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

Rename causing file access time to change

I am trying to move a file between directories on the same filesystem. The difficulty I am having is that when I use rename() the file access time is changed for that file on the filesystem.
I tried using shell_exec() with mv, though for some reason when I call mv in this way it copies the file and then deletes the original which takes much longer.
Is there any way to move the file quickly without changing the access time? Or can I change it back after calling rename()?
As a general rule the access time from a file must be changed when a function like rename(), or any other function that access a file, do it.
As for changing the access time of a file. This is only possible using the touch function, like described in the manual:
bool touch ( string $filename [, int $time = time() [, int $atime ]] )
Attempts to set the access and modification times of the file named in the filename parameter to the value given in time. Note that the access time is always modified, regardless of the number of parameters.
As you can see the time parameter is described in the manual as:
touch time
If time is not supplied, the current system time is used.
And here is an example from the same page of setting the access time one hour back from a file:
<?php
// This is the touch time, we'll set it to one hour in the past.
$time = time() - 3600;
// Touch the file
if (!touch('some_file.txt', $time)) {
echo 'Whoops, something went wrong...';
} else {
echo 'Touched file with success';
}
?>
However, be aware that the touch function, as described, attempts to change the file. If you have no permission for example the function will return false. (and won't change the file time)
Cheers
You can temporarily store the access time of the file using fileatime and modify it using touch.
$filename = 'somefile.txt';
$original_timestamp = fileatime($filename);
// .. modify file here ..
touch($filename, $original_timestamp);

Select a file that was created the last minute

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.

PHP: A good script to clear temporary file for cron?

I have a temporary folder generated by my business application and wish for the documents within to be only available for around 30 minutes. I was tempted to build an index to keep track of when each file was created but that would be a little silly for just temporary files, they are not of too much importance but I would like them to removed according to the time they were last modified.
What would I need to do this with my Linux server?
The function filemtime() will allow you to check the last modify date of a file. What you will need to do is run your cron job each minute and check if it is greater than the threshold and unlink() it as needed.
$time = 30; //in minutes, time until file deletion threshold
foreach (glob("app/temp/*.tmp") as $filename) {
if (file_exists($filename)) {
if(time() - filemtime($filename) > $time * 60) {
unlink($filename);
}
}
}
This should be the most efficient method as you requested, change the cron threshold to 10 minutes if you need a less accuracy in case there are many files.
You'd need nothing more than to call stat on the files and decide whether to unlink them or not based on their mtime.
Call this script every ten minutes or so from cron or anacron.
Or you could use tmpwatch, a program designed for this purpose.

Categories