ilvalentino4ever ilvalentino4ever - 3 months ago 11
Linux Question

How use filemtime to move all files by their last modified time

Referred to this question, I found difficulties using

filemtime();
to find out last modified time of files inside a folder.

I need to move all my files that are already inside
__DIR__ .'/../uploads/media';
to
__DIR__ .'/../uploads/media/YY/mm';
based on their last modified time.

Here my function:

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

}


What's wrong in my function? No files have been moved and only one folder was created (1970/01)

SOLUTION

Probably there are other better ways but here is my solution:

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

}

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

Why did you use filemtime on timestamp? try this:

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

and you should use rename instead of move_uploaded_file

Comments