简体   繁体   中英

Move/copy and rename most recently modified file

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM