rename folder into sub-folder with PHP

前端 未结 4 1948
醉酒成梦
醉酒成梦 2021-02-19 09:50

I\'m trying to move a folder by renaming it. Both the test1 and test2 folders already exist.

rename(
 \"test1\",
 \"test2/xxx1/xxx2\"
);

The e

4条回答
  •  说谎
    说谎 (楼主)
    2021-02-19 10:28

    Your assumption was correct, this is because "xxx1" in your example does not exist.

    So, before rename("oldname", "/some/long/nested/path/test2/xxx1/newname") you have to create directory tree structure: /some/long/nested/path/test2/xxx1/ but newname file (or directory) must not exist at the moment of rename function call.

    To generalize the solution look at the following naive function:

    function renameWithNestedMkdir($oldname , $newname)
    {
         $targetDir = dirname($newname); // Returns a parent directory's path (operates naively on the input string, and is not aware of the actual filesystem)
    
        // here $targetDir is "/some/long/nested/path/test2/xxx1"
        if (!file_exists($targetDir)) {
            mkdir($targetDir, 0777, true); // third parameter "true" allows the creation of nested directories
        }
    
        return rename($oldname , $newname);
    }
    
    // example call
    renameWithNestedMkdir("oldname", "/some/long/nested/path/test2/xxx1/newname");
    
    // another example call
    renameWithNestedMkdir("test1", "test2/xxx1/xxx2");
    

    I named this implementation "naive" because in real production you should also think about handling some edge cases: what if $newname already exists? What if /some/long/nested/path/test2/xxx1 already exists but it's a file (not a directory)? Why I put 0777 access rights while mkdir? What if mkdir failed?

提交回复
热议问题