当尝试将目录内容复制到另一个位置时,代码 copy ("old_location/*.*"," new_location/") 可能会遇到错误,指示未找到该流。当在复制函数中单独使用星号 (*) 时,可能会发生这种情况。
为了有效复制目录的全部内容(包括其子目录和文件),我们可以使用如下递归函数:
<code class="php">function recurseCopy( string $sourceDirectory, string $destinationDirectory, string $childFolder = '' ): void { // Open the source directory $directory = opendir($sourceDirectory); // Check if the destination directory exists, if not, create it if (is_dir($destinationDirectory) === false) { mkdir($destinationDirectory); } // If there's a child folder specified, create it if it doesn't exist if ($childFolder !== '') { if (is_dir("$destinationDirectory/$childFolder") === false) { mkdir("$destinationDirectory/$childFolder"); } // Loop through the files in the source directory while (($file = readdir($directory)) !== false) { // Ignore current and parent directories if ($file === '.' || $file === '..') { continue; } // If the current file is a directory, recursively copy it if (is_dir("$sourceDirectory/$file") === true) { recurseCopy("$sourceDirectory/$file", "$destinationDirectory/$childFolder/$file"); } // If it's a file, simply copy it else { copy("$sourceDirectory/$file", "$destinationDirectory/$childFolder/$file"); } } // Close the source directory closedir($directory); // Recursion ends here return; } // Loop through the files in the source directory while (($file = readdir($directory)) !== false) { // Ignore current and parent directories if ($file === '.' || $file === '..') { continue; } // If the current file is a directory, recursively copy it if (is_dir("$sourceDirectory/$file") === true) { recurseCopy("$sourceDirectory/$file", "$destinationDirectory/$file"); } // If it's a file, simply copy it else { copy("$sourceDirectory/$file", "$destinationDirectory/$file"); } } // Close the source directory closedir($directory); }</code>
通过使用这个递归函数,我们可以高效地将一个目录的全部内容复制到另一个位置,确保所有子目录和文件都正确传输。
以上是如何使用 PHP 递归复制目录的内容?的详细内容。更多信息请关注PHP中文网其他相关文章!