Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rename folder into sub-folder with PHP

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?

like image 943
Workoholic Avatar asked Apr 16 '10 14:04

Workoholic


2 Answers

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.

like image 161
Tom Haigh Avatar answered Sep 27 '22 20:09

Tom Haigh


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

like image 22
Andy Shellam Avatar answered Sep 27 '22 20:09

Andy Shellam