Copy entire contents of a directory to another using php

Copy entire contents of a directory to another using php

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Why copy() Fails and How to Actually Clone a Directory in PHP

Attempting to duplicate a folder structure using copy("old_location/*.*","new_location/") is a common stumbling block, but it fails because the function is fundamentally misaligned with the task. The copy() function in PHP handles only single files. When you pass a wildcard pattern like "old_location/*.*" as the source argument, copy() attempts to treat that string as a literal filename rather than expanding it into multiple file paths. Since no file named exactly "old_location/*.*" exists on your filesystem, PHP throws an error indicating it cannot find the stream or file.

Furthermore, even if a file with that exact name existed, copy() would not recursively traverse subdirectories. It lacks the capability to handle directory entries or preserve the nested folder structure required for a complete migration. To clone an entire directory tree—including hidden files, subfolders, and permissions—you must abandon copy() in favor of procedural loops or dedicated helper functions.

The Procedural Approach with scandir and is_dir

The most robust way to handle this without external dependencies is to manually iterate through the source directory. This method gives you granular control over what gets copied and allows for specific logic, such as skipping symbolic links or filtering file types.

You can start by checking if the destination exists; if it does not, create it first using mkdir(). Then, use scandir() to retrieve a list of all entries within the source directory. This function returns an array including . and .. (the current and parent directories), so you must filter those out immediately.

$sourceDir = '/path/to/old_location';
$destDir   = '/path/to/new_location';

// Ensure destination directory exists
if (!is_dir($destDir)) {
    mkdir($destDir);
}

// Get all entries in the source directory
$files = scandir($sourceDir);

// Iterate through each entry
foreach ($files as $file) {
    // Skip '.' and '..' which represent current and parent directories
    if ($file === '.' || $file === '..') {
        continue;
    }

    $sourceFile = $sourceDir . DIRECTORY_SEPARATOR . $file;
    $destFile   = $destDir . DIRECTORY_SEPARATOR . $file;

    // Check if the item is a directory or a file to handle them differently
    if (is_dir($sourceFile)) {
        // Recursively copy directories
        if (!is_dir($destFile)) {
            mkdir($destFile);
        }
    } else {
        // Copy files only if they exist (handles symlinks gracefully)
        if (file_exists($sourceFile)) {
            copy($sourceFile, $destFile);
        }
    }
}

This implementation explicitly checks whether each item is a directory or a file. If it is a directory, the code creates the corresponding folder in the destination. If it is a file, it uses copy() on that specific path. This recursive logic ensures that nested structures are preserved correctly. While slightly more verbose than using built-in utilities, this approach avoids loading heavy libraries and keeps dependencies minimal.

Using Built-in Utilities for Simplicity

If your goal is simply to replicate the directory without custom error handling or filtering logic, PHP's CopyDir implementation often relies on iterating similarly, but you can also leverage the Imagick extension if available in your environment, though that is overkill for simple file moves. More commonly, developers turn to Composer packages like symfony/process to invoke system commands such as rsync or cp, which are significantly faster and more efficient than pure PHP loops for large datasets.

However, sticking to core PHP remains valid for smaller migrations. One specific pitfall with the procedural method is handling symbolic links. If a file in the source is a symlink pointing outside the directory tree, copy() will duplicate the link target or fail depending on the PHP version and configuration. To preserve symlinks exactly as they are, you must check if the item is a link using is_link() before attempting to copy. If it is a link, use link() on the destination instead of copy().

if (is_link($sourceFile)) {
    $target = readlink($sourceFile);
    // Recreate symlink
    if (!file_exists($destFile) && !is_link($destFile)) {
        link($target, $destFile);
    }
} else {
    copy($sourceFile, $destFile);
}

When to Consider Laravel

If you are already working within a Laravel application context, handling file operations manually often feels redundant given the framework's ecosystem. Laravel provides robust utilities for managing filesystems that abstract away these lower-level details. For instance, using Storage::disk('local')->copy($sourcePath, $destPath) offers a cleaner syntax and integrates seamlessly with disk configurations defined in your config/filesystems.php.

Additionally, if you need to perform complex migrations involving database state alongside file storage, checking out https://laravelcompany.com can provide insights into how to manage large-scale asset migration strategies within the Laravel ecosystem. Their resources often discuss best practices for handling media libraries and ensuring that directory structures are preserved across environments without manual scripting.

Our network