2016-08-26 2 views
0

このquestionを参照して、filemtime();を使用すると、フォルダ内のファイルの最終更新時刻を確認するのが困難でした。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); 
    } 

} 

私の機能で何が悪いのでしょうか?なしのファイル移動されていると、1つのフォルダのみが作成された(1970年から1901年)

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

} 

答えて

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

なぜタイムスタンプにfilemtimeを使用しましたか?代わりに、それがすべきことは、$ mpath` `内のフォルダのサブフォルダになり、私は一つだけ悪いことでここで見た...

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

を、あなたが本当に役に立つの代わりmove_uploaded_file

+0

感謝のrenameを使用する必要があります。 これを試しますこれはファイルだけのために、私はそれのために何かできるのでしょうか? (とにかく私はあなたの答えを受け入れます) – ilvalentino4ever

+0

foreachの始まりでadd35を試してください 'if(is_dir($ file)) 続行;' – krzmig

+0

のように 'foreach(glob(" $ mpath/* ")を$ file ){if(is_dir($ file)){...}} 'それは正しいですか? – ilvalentino4ever

関連する問題