【问题标题】:Best way to move entire directory tree in PHP在 PHP 中移动整个目录树的最佳方法
【发布时间】:2012-09-02 11:09:29
【问题描述】:

我想将文件从一个目录移动到另一个目录。但是,诀窍是,我想移动带有完整路径的文件。

假设我在

有文件
/my/current/directory/file.jpg

我想把它移到

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

如您所见,我想保留相对路径,以便将来如果需要,我可以将其移回/my/current/directory/。还有一件事是/newfolder 是空的 - 我可以复制其中的任何内容,因此没有预制结构(另一个文件可能被复制到/newfolder/my/another/folder/anotherfile.gif。理想情况下,我希望能够创建一个可以做到的方法当我将原始路径传递给它时的魔力。目的地总是一样的 - /newfolder/...

【问题讨论】:

  • 可以执行系统命令,还是要在php中执行?

标签: php copy directory file-rename


【解决方案1】:

如果你在 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';

【讨论】:

  • 这是我最初的想法 - 我只是错过了 dirname() 的存在,它似乎有点麻烦。除此之外,它就像一个魅力。为什么是-1?
  • 因为我写的是move()而不是rename(),所以我当然更新了!
【解决方案2】:

你可以简单地使用以下

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

请注意我使用反引号`来执行而不是使用像exec这样的函数

【讨论】:

  • echo ($output) ? 'fail' : 'success'; ;)
  • 对不起,但在我的测试中,如果目标目录不存在,它不会复制文件。
猜你喜欢
  • 2013-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-09
  • 1970-01-01
  • 2015-04-27
  • 1970-01-01
相关资源
最近更新 更多