Reputation: 63
I have a folder with some randomly named files that contain data that I need.
In order to use the data, I have to move the files to another folder and name the file 'file1.xml'
Every time a file is moved and renamed, it replaces a previous 'file1.xml' in the destination folder.
The source folder contains all the other randomly named files which are kept as an archive.
The php will be run via a cron job every 48 hours
The following works, but it's for ftp. I need to edit it for local files.
$conn = ftp_connect('ftp.source.com'); ftp_login($conn, 'username', 'password'); // get file list $files = ftp_nlist($conn, '/data'); $mostRecent = array( 'time' => 0, 'file' => null ); foreach ($files as $file) { // get the last modified time $time = ftp_mdtm($conn, $file); if ($time > $mostRecent['time']) { // this file is the most recent so far $mostRecent['time'] = $time; $mostRecent['file'] = $file; } } ftp_get($conn, "/destinationfolder/file1.xml", $mostRecent['file'], FTP_BINARY); ftp_close($conn);
Upvotes: 2
Views: 96
Reputation: 344
I didn't test it but I think this should work (comparing your ftp script):
<?php
$conn = ftp_connect('ftp.source.com');
ftp_login($conn, 'username', 'password');
// get file list
$files = ftp_nlist($conn, '/data');
$mostRecent = array( 'time' => 0, 'file' => null );
foreach ($files as $file) {
// get the last modified time
$time = ftp_mdtm($conn, $file);
if ($time > $mostRecent['time']) {
// this file is the most recent so far
$mostRecent['time'] = $time;
$mostRecent['file'] = $file;
}
}
ftp_get($conn, "/destinationfolder/file1.xml", $mostRecent['file'], FTP_BINARY); ftp_close($conn);
?>
New:
<?php
$sourceDir = "./data";
$destDir = "./destinationfolder";
if (!is_dir($sourceDir) || !is_dir($destDir)) {
exit("Directory doesn't exists.");
}
if (!is_writable($destDir)) {
exit("Destination directory isn't writable.");
}
$mostRecentFilePath = "";
$mostRecentFileMTime = 0;
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($sourceDir), RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
if ($fileinfo->getMTime() > $mostRecentFileMTime) {
$mostRecentFileMTime = $fileinfo->getMTime();
$mostRecentFilePath = $fileinfo->getPathname();
}
}
}
if ($mostRecentFilePath != "") {
if (!rename($mostRecentFilePath, $destDir . "/file1.xml")) {
exit("Unable to move file.");
}
}
?>
Upvotes: 2