copy a directory in php

You can copy a directory in PHP by using the copy() function recursively. Here's a code snippet to demonstrate:

main.php
function copyDirectory($source, $destination) {
    // Check if source exists
    if (!file_exists($source)) {
        return false;
    }

    // Create destination directory if it doesn't exist
    if (!is_dir($destination)) {
        mkdir($destination);
    }

    // Open the source directory
    $dir = opendir($source);

    // Loop through the files in the source directory
    while ($file = readdir($dir)) {
        if ($file != "." && $file != "..") {
            if (is_dir($source . DIRECTORY_SEPARATOR . $file)) {
                // Recursively copy sub-directory
                copyDirectory($source . DIRECTORY_SEPARATOR . $file, $destination . DIRECTORY_SEPARATOR . $file);
            } else {
                // Copy file to destination directory
                copy($source . DIRECTORY_SEPARATOR . $file, $destination . DIRECTORY_SEPARATOR . $file);
            }
        }
    }

    // Close source directory
    closedir($dir);
    return true;
}
972 chars
32 lines

You can call this function with the source directory as the first parameter and the destination directory as the second parameter:

main.php
$sourceDir = '/path/to/source/directory';
$destDir = '/path/to/destination/directory';
copyDirectory($sourceDir, $destDir);
124 chars
4 lines

This will copy the entire contents of the source directory to the destination directory recursively.

gistlibby LogSnag