简体   繁体   English

将文件从一个文件夹复制到另一个

[英]copy file from one folder to other

I want to move all files from one folder to other. 我想将所有文件从一个文件夹移动到另一个文件夹。 my code is as following. 我的代码如下。 in this I made a folder in which i want to copy all file from templats folder 在此我创建了一个文件夹,我要在其中复制模板文件夹中的所有文件

$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);
}

It working fine . 它工作正常。 copy all files but give warning that The first argument to copy() function cannot be a directory 复制所有文件,但发出警告,copy()函数的第一个参数不能为目录

can any one help me asap 谁能尽快帮助我

Readdir will read all children in a directory, including other dirs, and 'virtual' dirs like . Readdir将读取目录中的所有子目录,包括其他目录和“虚拟”目录,如。 and .. (link to root and parent dir, resp.) You'll have to check for these and prevent the copy() function for these instances. 和..(分别链接到根目录和父目录)。您必须检查这些内容并阻止这些实例的copy()函数。

while (($file = readdir($dir)) !== false)
{
    if(!is_dir($file))
    {
        copy($source.$file, $target.$file);
    }
}
if ($file != "." && $file != "..") {
// copy
}

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." 这意味着它尝试复制的第一件事是“ \\ template”。 which would be the same as trying to copy the directory. 这与尝试复制目录相同。

Just add something like: 只需添加如下内容:

if ($file !== "." && $file !== "..")
...

opendir() will include items . opendir()将包含items . and .. as per the documentation . ..根据文档

You will need to exclude these by using the code in the other comments. 您将需要使用其他注释中的代码排除这些。

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. 同时,Objects引入了更多的功能和可能性。 Needless to say, the other answers will still work aswell. 不用说,其他答案也将仍然有效。

But here we go, using the DirectoryIterator : 但是在这里,我们使用DirectoryIterator

$szSrcFolder = 'source_folder';
$szTgtFolder = 'target_folder';

foreach (new DirectoryIterator($szSrcFolder) as $oInfo)
    if ($oInfo->isFile())
        copy($oInfo->getPathname(), $szTgtFolder . DIRECTORY_SEPARATOR . $oInfo->getBasename());

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. 这几行将遍历源文件夹的整个内容,并检查它是否是文件,并将其复制到目标文件夹,并保留原始文件名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM