命令 copy ("old_location/*.*","new_location/ ") 失败,因为通配符 (*.*) 不能被 copy() 直接识别
要复制整个目录的内容,包括子目录和文件,需要递归复制函数。下面是一个示例:
<code class="php">function recurseCopy(string $sourceDirectory, string $destinationDirectory, string $childFolder = ''): void { $directory = opendir($sourceDirectory); if (is_dir($destinationDirectory) === false) { mkdir($destinationDirectory); } if ($childFolder !== '') { if (is_dir("$destinationDirectory/$childFolder") === false) { mkdir("$destinationDirectory/$childFolder"); } while (($file = readdir($directory)) !== false) { if ($file === '.' || $file === '..') { continue; } if (is_dir("$sourceDirectory/$file") === true) { recurseCopy("$sourceDirectory/$file", "$destinationDirectory/$childFolder/$file"); } else { copy("$sourceDirectory/$file", "$destinationDirectory/$childFolder/$file"); } } closedir($directory); return; } while (($file = readdir($directory)) !== false) { if ($file === '.' || $file === '..') { continue; } if (is_dir("$sourceDirectory/$file") === true) { recurseCopy("$sourceDirectory/$file", "$destinationDirectory/$file"); } else { copy("$sourceDirectory/$file", "$destinationDirectory/$file"); } } closedir($directory); }</code>
要使用此函数,请使用源目录、目标目录和可选子文件夹(如果需要)来调用它。
<code class="php">recurseCopy("old_location", "new_location");</code>
以上是如何使用 PHP 复制目录内容?的详细内容。更多信息请关注PHP中文网其他相关文章!