How to copy a directory and its contents to another location in PHP?

To copy a directory and its contents to another location using PHP, you can use the recursiveIteratorIterator and recursiveDirectoryIterator classes from the SPL (Standard PHP Library) along with some basic file operations. Here's an example code snippet:

function recursiveCopy($src, $dst) { $dir = opendir($src); @mkdir($dst); while (($file = readdir($dir)) !== false) { if ($file != '.' && $file != '..') { $srcFile = $src . '/' . $file; $dstFile = $dst . '/' . $file; if (is_dir($srcFile)) { recursiveCopy($srcFile, $dstFile); } else { copy($srcFile, $dstFile); } } } closedir($dir); }

To use the above function, you just need to call it with the source and destination directories as parameters:

$srcDir = '/path/to/source/directory'; $dstDir = '/path/to/destination/directory'; recursiveCopy($srcDir, $dstDir);

Make sure to replace /path/to/source/directory and /path/to/destination/directory with the actual paths of your source directory and destination directory respectively.