簡體   English   中英

在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/...

您可以簡單地使用以下內容

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

請注意,我正在使用反引號`來執行,而不是使用exec這樣的函數

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM