Home > Article > Backend Development > How to Recursively Copy Directory Contents in PHP?
Copying Directory Contents with PHP
Copying the entire contents of a directory to another location in PHP can be a straightforward task, but running into issues like stream not found error can be frustrating. To avoid this, a more explicit approach is required.
To overcome the limitations of using wildcards in the copy() function, a recursive function named recurseCopy() can be employed. This function allows for the replication of multi-level directory structures and their contents.
The recurseCopy() function takes three parameters:
The function iterates through the files and subdirectories of the source directory. If a file is encountered, it is directly copied to the destination directory. If a subdirectory is found, the function recursively calls itself to copy its contents into the corresponding subdirectory under the destination directory.
Here's a sample PHP code that utilizes the recurseCopy() function:
<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); } $sourceDirectory = 'my_source_dir'; $destinationDirectory = 'my_destination_dir'; recurseCopy($sourceDirectory, $destinationDirectory);</code>
This code will recursively copy the contents of the my_source_dir directory to the my_destination_dir directory, preserving the directory structure and file contents.
The above is the detailed content of How to Recursively Copy Directory Contents in PHP?. For more information, please follow other related articles on the PHP Chinese website!