Search code examples
phprenamemove

Move file to directory


So with your help I have been able to assemble the below.

$dir = "./reporting/live-metrics/";
$des = "./reporting/historic-metrics/";
$ctime = time(); 

foreach (glob($dir."*") as $file) {

$live = file_get_contents($file);

if (strpos($live, 'CORO') === false && filemtime($file) < time() - 1 * 10) {
$exclude[] = $live;
$lines = file( $file , FILE_IGNORE_NEW_LINES );
$lines[3] = 'Taken Down';
$lines[5] = $ctime;
file_put_contents( $file , implode( "\n", $lines ) );
if (!file_exists($des.basename($file).PHP_EOL)) {
mkdir($des.basename($file), 0777, true);
}
rename($file,$des.$ctime);
}
}

My issue is that I am attempting to move the file to the new directory created but I am having a little issue with it. No matter what I do I can only get it to move to $des, i cant seem to get ti to move to the dynamicaly created directory for each specific file. I am assuming it has to do with the fact I am not using rename to its correct params. Below are the some of the combinations I have tried to get it to rename and move.

rename($file,$des.basename($file).PHP_EOL.$ctime); //doesn't move or rename
rename($file,$des.basename($file).$ctime); //adds to historic-metrics/ as jason1465519298

I also tried creating a function and setting the rename to call on that. eg.

$path = $des.basename($file).PHP_EOL;
rename($file,$path.$ctime);

Currently the script is great up until the moving the file. It will move it to ./reporting/historic-metrics/ but I would like it to move to the directory just created. EG, if the file it is currently handeling is called 'Jason' then it will create ./reporting/historic-metrics/Jason but move the file to ./reporting/historic-metrics/


Solution

  • I finally got it. My main issue was trying to get the filepath to send the file to. After a few interruptions and rethinking my approach I came up with the below. I know it isn't pretty or as slim as could be made but it does the job perfectly.

    $dir = "./reporting/live-metrics/";
    $des = "./reporting/historic-metrics/";
    $ctime = time(); 
    
    foreach (glob($dir."*") as $file) {
    
    $live = file_get_contents($file);
    
    if (strpos($live, 'CORO') === false && filemtime($file) < time() - 1 * 10) {
        $exclude[] = $live; 
        $lines = file( $file , FILE_IGNORE_NEW_LINES );
        $lines[3] = 'Taken Down'; 
        $lines[5] = $ctime; 
        file_put_contents( $file , implode( "\n", $lines ) ); 
        if (!file_exists($des.basename($file).PHP_EOL)) { 
        mkdir($des.basename($file), 0777, true);
    }
    $user = basename($file); //Gets file name that was used in mkdir
    $path = (String) $des.$user."/"; //Compiles variables into string
        rename($file,$path.$ctime);
    }
    }