将文件从一个文件夹复制到另一个文件夹
我想将所有文件从一个文件夹移动到另一个文件夹。我的代码如下。在此我创建了一个文件夹,我想在其中复制模板文件夹中的所有文件,
$doit = str_replace(" ", "", $slt['user_compeny_name']);
mkdir("$doit");
$source = "templat/";
$target = $doit . "/";
$dir = opendir($source);
while (($file = readdir($dir)) !== false) {
copy($source . $file, $target . $file);
}
它工作正常。复制所有文件,但警告 copy() 函数的第一个参数不能是目录,
任何人都可以尽快帮助我
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Readdir 将读取目录中的所有子目录,包括其他目录和“虚拟”目录,例如 .和..(分别链接到根目录和父目录)您必须检查这些并阻止这些实例的
copy()
函数。Readdir will read all children in a directory, including other dirs, and 'virtual' dirs like . and .. (link to root and parent dir, resp.) You'll have to check for these and prevent the
copy()
function for these instances.您没有考虑目录顶部的
.
和..
文件。这意味着它尝试复制的第一个内容是“\template”。这与尝试复制目录相同。只需添加类似以下内容:
You are not accounting for the
.
and the..
files at the top of the directory. This means that the first thing it tries to copy is "\template." which would be the same as trying to copy the directory.Just add something like:
opendir()
将根据 . 和..
="nofollow noreferrer">文档。您需要使用其他注释中的代码来排除这些内容。
opendir()
will include items.
and..
as per the documentation.You will need to exclude these by using the code in the other comments.
我知道,这个问题很老了,但也有答案。我觉得有必要展示一些新方法,这些方法可用于执行请求的任务。
与此同时,对象被引入了更多的功能和可能性。不用说,其他答案仍然有效。
但我们在这里使用 DirectoryIterator:
记住,在此脚本中,所有路径都相对于脚本本身的工作目录。
我认为这是不言自明的,但我们会看一下。这几行将迭代源文件夹的全部内容,检查它是否是一个文件,并将其复制到目标文件夹,保留原始文件名。
I know, this question is pretty old, but also are the answers. I feel the need to show some new methods, which can be used to execute the requested task.
In the mean time Objects were introduced with a lot more features and possibilities. Needless to say, the other answers will still work aswell.
But here we go, using the DirectoryIterator:
Remember, within this script, all paths are relative to the working directory of the script itself.
I think it is self explaining, but we will take a look. This few lines will iterate over the whole content of the source folder and check if it is a file and will copy it to the target folder, keeping the original file name.