在PHP中移动整个目录树的最佳方式


Best way to move entire directory tree in PHP

我想将文件从一个目录移动到另一个目录。然而,诀窍是,我想移动文件的整个路径

假设我在有文件

/my/current/directory/file.jpg

我想把它移到

/newfolder/my/current/directory/file.jpg

正如你所看到的,我想保留相对路径,这样在未来,如果我需要的话,我可以将其移回/my/current/directory/。还有一件事是/newfolder是空的-我可以复制其中的任何内容,因此没有预先制作的结构(另一个文件可能会复制到/newfolder/my/another/folder/anotherfile.gif。理想情况下,我希望能够创建一个方法,当我将文件的原始路径传递给它时,它会发挥神奇的作用。目标总是一样的-/newfolder/...

如果您在unix/linux环境中,您可以尝试这样的操作:

$original_file = '/my/current/directory/file.jpg';
$new_file = "/newfolder{$original_file}";
// create new diretory stricture (note the "-p" option of mkdir)
$new_dir = dirname($new_file);
if (!is_dir($new_dir)) {
    $command = 'mkdir -p ' . escapeshellarg($new_dir);
    exec($command);
}
echo rename($original_file, $new_file) ? 'success' : 'failed';

您可以简单地使用以下

<?php 
$output = `mv "/my/current/directory/file.jpg" "/newfolder/my/current/directory/file.jpg"`; 
if ($output == 0) { 
   echo "success"; 
} else { 
   echo "fail"; 
} 
?>

请注意,我使用backtick`来执行,而不是使用exec 这样的函数