如何使用filemtime按上次修改时间移动所有文件

时间:2016-08-26 09:36:46

标签: php linux

提到此question,我发现使用filemtime();查找文件夹中文件的上次修改时间时遇到了困难。

我需要根据上次修改时间将__DIR__ .'/../uploads/media';内的所有文件移至__DIR__ .'/../uploads/media/YY/mm';

这是我的功能:

function grab_pictures() {
    $mpath = __DIR__ .'/../uploads/media';

    foreach (glob("$mpath/*") as $file) { 
        //find timestamp of last modified time
        $lastmoddate = filemtime($file);
        //grab only the filename with extension for newPath
        $basename = basename($file);  
        //takes month from timestamp   
        $month = date("m", filemtime($lastmoddate));
        //takes Year from timestamp  
        $year = date("Y", filemtime($lastmoddate));
        //creates new folders /Year/month/ based on last modified time of each file
        $newPath = __DIR__ .'/../uploads/media/' .$year. '/' .$month. '/';

        if (!is_dir($newPath)) {
            mkdir($newPath, 0775, true);
        }

        $newName = '/' .$year. '/' .$month. '/' .$basename;

        //change path in MySQL
        $this->db->query(sprintf("UPDATE `images` SET `path` = '%s', `time` = 'time'", $newName));

        // Move files from old to the new path
        move_uploaded_file($basename, $newPath);
    }

}

我的功能出了什么问题?没有文件被移动,只创建了一个文件夹(1970/01)

可能还有其他更好的方法,但这是我的解决方案:

function grab_pictures() {
    $mpath = __DIR__ .'/../uploads/media';

    foreach (glob("$mpath/*") as $file) { 
        $lastmoddate = filemtime($file);
        $basename = basename($file);     
        $month = date("m", $lastmoddate);
        $year = date("Y", $lastmoddate);
        $newPath = __DIR__ .'/../uploads/media/' .$year. '/' .$month. '/';

        if (!is_dir($newPath)) {
            mkdir($newPath, 0775, true);
        }

        $newName = '/' .$year. '/' .$month. '/' .$basename;

        $old_Path = $mpath. '/' .$basename;
        $new_Path = $mpath.$newName;

        $this->db->query(sprintf("UPDATE `images` SET `path` = '%s', `time` = `time` WHERE `art` = '%s'", $newName,$basename));

        // Move the file
        rename($old_Path, $new_Path);
    }

}

1 个答案:

答案 0 :(得分:1)

//takes month from timestamp   
$month = date("m", filemtime($lastmoddate));
//takes Year from timestamp  
$year = date("Y", filemtime($lastmoddate));

为什么在时间戳上使用filemtime? 试试这个:

//takes month from timestamp   
$month = date("m", $lastmoddate);
//takes Year from timestamp  
$year = date("Y", $lastmoddate);

您应该使用rename代替move_uploaded_file