使用 PHP 将文件夹重命名为子文件夹
我正在尝试通过重命名来移动文件夹。 test1 和 test2 文件夹均已存在。
rename(
"test1",
"test2/xxx1/xxx2"
);
我得到的错误是:重命名(...):没有这样的文件或目录
我认为这是因为目录“xxx1”不存在。 我怎样才能移动 test1 目录?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能需要创建它要进入的目录,例如
mkdir 的第三个参数()
是“递归”的,这意味着您可以通过一次调用创建嵌套目录。You might need to create the directory it is going into, e.g.
The third parameter to
mkdir()
is 'recursive', which means you can create nested directories with one call.为什么不首先通过创建父目录来确保所有父目录都存在? mkdir - 使用递归参数。
Why not make sure all parent directories exist first, by making them? mkdir - use the recursive parameter.
您的假设是正确的,这是因为您的示例中的“xxx1”不存在。
因此,在
rename("oldname", "/some/long/nested/path/test2/xxx1/newname")
之前,您必须创建目录树结构:/some/long/nested /path/test2/xxx1/
但在rename
函数调用时newname
文件(或目录)不得存在。为了概括该解决方案,请查看以下朴素函数:
我将此实现命名为“朴素”,因为在实际生产中,您还应该考虑处理一些边缘情况:如果 $newname 已经存在怎么办?如果
/some/long/nested/path/test2/xxx1
已经存在但它是一个文件(而不是目录)怎么办?为什么我在 mkdir 时放置 0777 访问权限?如果 mkdir 失败怎么办?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/
butnewname
file (or directory) must not exist at the moment ofrename
function call.To generalize the solution look at the following naive function:
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?我认为 test2/xxx1 需要存在,因此在移动它之前需要使用 mkdir 。
I think test2/xxx1 would need to exist, so you'd need to use mkdir before you move it.