在foreach循环中使用copy()复制多个文件php



我正在尝试使用copy()将多个文件从Web服务器上的一个域复制到另一个域,并通过文件列表进行循环,但它仅在列表中复制列表中的最后一个文件。

这是files-list.txt的内容:

/templates/template.php
/admin/admin.css
/admin/codeSnippets.php
/admin/editPage.php
/admin/index.php
/admin/functions.php
/admin/style.php
/admin/editPost.php
/admin/createPage.php
/admin/createPost.php
/admin/configuration.php

此脚本在我试图将文件复制到的网站上运行。这是脚本:

$filesList = file_get_contents("http://copyfromhere.com/copythesefiles/files-list.txt");
$filesArray = explode("n", $filesList);
foreach($filesArray as $file) {
    $filename = trim('http://copyfromhere.com/copythesefiles' . $file);
    $dest = "destFolder" . $file;
    if(!@copy($filename, $dest))
    {
        $errors= error_get_last();
        echo "COPY ERROR: ".$errors['type'];
        echo "<br />n".$errors['message'];
    } else {
        echo "$filename copied to $dest from remote!<br/>";
    }
}

我会像应有的那样单独地收到每个文件的肯定消息,但是当我检查目录时,只有来自files-list.txt的最后一个文件就在那里。我已经尝试更改订单,所以我知道问题在于脚本,而不是任何个人文件。

回声语句的输出看起来像这样:

http://copyfromhere.com/copythesefiles/admin/admin.css copied to updates/admin/editPage.php from remote!
http://copyfromhere.com/copythesefiles/admin/admin.css copied to updates/admin/editPost.php from remote!
http://copyfromhere.com/copythesefiles/admin/admin.css copied to updates/admin/index.php from remote!

etc

我已经稍作修改了您的代码,并在我的本地开发服务器上对其进行了测试。以下似乎有效:

$fileURL = 'http://copyfromhere.com/copythesefiles';
$filesArray = file("$fileURL/files-list.txt", FILE_IGNORE_NEW_LINES);
foreach ($filesArray as $file) {
  $fileName = "$fileURL/$file";
  $dest = str_replace($fileURL, 'destFolder', $fileName);
  if (!copy($fileName, $dest)) {
    $errors= error_get_last();
    echo "COPY ERROR: ".$errors['type'];
    echo "<br />n".$errors['message'];
  }
  else {
    echo "$fileName copied to $dest from remote!<br/>";
  }
}

这使用标记B指出的相同修复程序,但也将代码合并了一点。

除非您是从该远程站点获取的数据在路径/文件名中具有领导/,否则您不会生成适当的路径:

$file = 'foo.txt'; // example only
$dest = "destFolder" . $file;

生产destFolderfoo.txt,您最终会用一堆奇怪的文件名乱扔脚本的工作目录。也许你想要

$dest = 'destFolder/' . $file;
                   ^----note this

而不是。

最新更新