php PHP将一个目录中的所有文件复制到另一个目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19148427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:55:03  来源:igfitidea点击:

PHP copy all files in a directory to another?

php

提问by Panny Monium

I am trying to copy files to from a specific folder ($src) to a specific destination ($dst). I obtained the code from this tutorial here. I can't seem to manage to copy any files within the source directory.

我正在尝试将文件从特定文件夹 ($src) 复制到特定目标 ($dst)。我从本教程这里获得了代码。我似乎无法复制源目录中的任何文件。

<?php


$src = 'pictures';
$dst = 'dest';

function recurse_copy($src,$dst) { 
    $dir = opendir($src); 
    @mkdir($dst); 
    while(false !== ( $file = readdir($dir)) ) { 
        if (( $file != '.' ) && ( $file != '..' )) { 
            if ( is_dir($src . '/' . $file) ) { 
                recurse_copy($src . '/' . $file,$dst . '/' . $file); 
            } 
            else { 
                copy($src . '/' . $file,$dst . '/' . $file); 
            } 
        } 
    } 
    closedir($dir); 
} 

?>

I am not getting any errors for the above code.

我没有收到上述代码的任何错误。

回答by Panny Monium

I just tried this and it worked for me like a charm.

我刚试过这个,它对我很有用。

<?php

$src = 'pictures';
$dst = 'dest';
$files = glob("pictures/*.*");
      foreach($files as $file){
      $file_to_go = str_replace($src,$dst,$file);
      copy($file, $file_to_go);
      }

?>

回答by Mike Brant

I would just use shell command to do this if you don't have any special treatment you are trying to do (like filtering certain files or whatever).

如果您没有尝试进行任何特殊处理(例如过滤某些文件或其他任何内容),我将仅使用 shell 命令来执行此操作。

An example for linux:

一个Linux的例子:

$src = '/full/path/to/src'; // or relative path if so desired 
$dst = '/full/path/to/dst'; // or relative path if so desired
$command = 'cp -a ' . $src . ' ' .$dst;
$shell_result_output = shell_exec(escapeshellcmd($command));

Of course you would just use whatever options are available to you from shell command if you want to tweak the behavior (i.e. change ownership, etc.).

当然,如果您想调整行为(即更改所有权等),您可以使用 shell 命令中可用的任何选项。

This should also execute much faster than your file-by-file recursive approach.

这也应该比逐文件递归方法执行得快得多。