rename folder into sub-folder with PHP

前端 未结 4 1894
醉酒成梦
醉酒成梦 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:19

    I think test2/xxx1 would need to exist, so you'd need to use mkdir before you move it.

    0 讨论(0)
  • 2021-02-19 10:22

    Why not make sure all parent directories exist first, by making them? mkdir - use the recursive parameter.

    0 讨论(0)
  • 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?

    0 讨论(0)
  • 2021-02-19 10:30

    You might need to create the directory it is going into, e.g.

    $toName = "test2/xxx1/xxx2";
    
    if (!is_dir(dirname($toName))) {
        mkdir(dirname($toName), 0777, true);
    }
    
    rename("test1", $toName);
    

    The third parameter to mkdir() is 'recursive', which means you can create nested directories with one call.

    0 讨论(0)
提交回复
热议问题