简体   繁体   English

移动/复制和重命名最近修改的文件

[英]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'为了使用数据,我必须将文件移动到另一个文件夹并将文件命名为“file1.xml”

Every time a file is moved and renamed, it replaces a previous 'file1.xml' in the destination folder.每次移动和重命名文件时,它都会替换目标文件夹中以前的“file1.xml”。

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 php 将每 48 小时通过 cron 作业运行一次

The following works, but it's for ftp.以下工作,但它是为 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):我没有测试它,但我认为这应该有效(比较你的 ftp 脚本):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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