views:

210

answers:

4

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

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

The error I get is: rename(...): No such file or directory

I assume this is because the directory "xxx1" does not exist. How can I move the test1 directory anyway?

A: 

You must create her directory tree.

Svisstack
A: 

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

Andy Shellam
+1  A: 

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

$toName = "test2/xxx1/xxx2";

if (! dir_exists(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.

Tom Haigh
Won't the rename fail if the directory already exists?Both "xxx1" and "xxx2" are directories, and the second parameter might as well be "xxx2/"...
Workoholic
it will fail if the target `$toName` exists, but wouldn't you have had that problem with your original code anyway?
Tom Haigh
A: 

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

Josh