move all files in a folder to another?

前端 未结 11 1979
一个人的身影
一个人的身影 2020-12-01 04:01

when moving one file from one location to another i use

rename(\'path/filename\', \'newpath/filename\');

how do you move all files in a fol

11条回答
  •  执笔经年
    2020-12-01 04:18

    Not sure if this helps anyone or not, but thought I'd post anyway. Had a challenge where I has heaps of movies I'd purchased and downloaded through various online stores all stored in one folder, but all in their own subfolders and all with different naming conventions. I wanted to move all of them into the parent folder and rename them all to look pretty. all of the subfolders I'd managed to rename with a bulk renaming tool and conditional name formatting. the subfolders had other files in them i didn't want. so i wrote the following php script to, 1. rename/move all files with extension mp4 to their parent directory while giving them the same name as their containing folder, 2. delete contents of subfolders and look for directories inside them to empty and then rmdir, 3. rmdir the subfolders.

    $handle = opendir("D:/Movies/");
    while ($file = readdir($handle)) {
    if ($file != "." && $file != ".." && is_dir($file)) {
        $newhandle = opendir("D:/Movies/".$file);
        while($newfile = readdir($newhandle)) {
            if ($newfile != "." && $newfile != ".." && is_file("D:/Movies/".$file."/".$newfile)) {
                $parts = explode(".",$newfile);
                if (end($parts) == "mp4") {
                    if (!file_exists("D:/Movies/".$file.".mp4")) {
                        rename("D:/Movies/".$file."/".$newfile,"D:/Movies/".$file.".mp4");
                    }
                    else {
                        unlink("D:/Movies/".$file."/".$newfile);
                    }
                }
                else { unlink("D:/Movies/".$file."/".$newfile); }
            }
            else if ($newfile != "." && $newfile != ".." && is_dir("D:/Movies/".$file."/".$newfile)) {
                $dirhandle = opendir("D:/Movies/".$file."/".$newfile);
                while ($dirfile = readdir($dirhandle)){
                    if ($dirfile != "." && $dirfile != ".."){
                        unlink("D:/Movies/".$file."/".$newfile."/".$dirfile);
                    }
                }
                rmdir("D:/Movies/".$file."/".$newfile);
            }
        }
        unlink("D:/Movies/".$file);
    }
    }
    

提交回复
热议问题