move all files in a folder to another?

move all files in a folder to another?

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

Stefan Bogdanescu

Founder & Senior Architect

Why rename() Fails on Directory Contents and How to Fix It

In PHP, moving a single file is straightforward. The rename() function accepts two paths: the source and the destination. If you know exactly where a file lives, you can slide it across with one line of code.

rename('path/filename', 'newpath/filename');

This works because the filesystem treats a filename as an opaque object. As long as the source exists and the destination directory is writable, the operation atomically shifts the inode from one location to another. It's fast, efficient, and requires no iteration.

However, developers often face a different scenario: they need to move every file inside a folder to a new parent directory. The intuitive approach is to assume rename() supports wildcard expansion. You might try passing a glob pattern directly to the function:

rename('path/*', 'newpath/*');

This fails immediately. The rename() function does not interpret wildcards like *. It expects concrete, absolute paths for both arguments. When you pass 'path/*', PHP treats it as a literal string containing an asterisk character, not a pattern matching multiple files. Since no file named literally path/* exists, the function returns false.

To move all files in a directory, you must explicitly iterate over the contents of the source folder and handle each item individually. This approach requires retrieving the list of entries and then deciding how to process them.

Iterating with scandir() or glob()

The most robust method is to use scandir() to list the directory's contents, filter out directories if necessary, and pass each file path to rename().

$sourceDir = '/path/to/source';
$destDir   = '/new/path';

if (!is_dir($sourceDir)) {
    throw new RuntimeException("Source directory does not exist.");
}

// Retrieve all entries including subdirectories and hidden files
$entries = scandir($sourceDir);

foreach ($entries as $item) {
    // Skip '.' and '..' which represent the current and parent directories
    if ($item === '.' || $item === '..') {
        continue;
    }

    $sourcePath = rtrim($sourceDir, '/') . '/' . $item;
    
    // Determine the destination path. 
    // If you want to preserve directory structure inside the new folder:
    $destPath = rtrim($destDir, '/') . '/' . $item;

    if (rename($sourcePath, $destPath)) {
        // File moved successfully
    } else {
        // Handle error: check permissions or disk space
        throw new RuntimeException("Failed to move {$item}");
    }
}

This loop ensures that every file is addressed individually. If a subdirectory exists in the source, you must decide whether to move it as well. The example above moves files regardless of type, but if you strictly want files, you can check is_file() before attempting the move.

Preserving Subdirectory Structure

A common requirement when migrating data is maintaining the internal structure of the folder tree. If your source directory contains subfolders, simply renaming them into the root of the new destination might not be desired.

To preserve the hierarchy, you calculate a relative path for each item and append it to the destination base:

$sourceDir = '/path/to/source';
$destDir   = '/new/path';

// Ensure destination exists
if (!is_dir($destDir)) {
    mkdir($destDir, 0755, true);
}

$entries = scandir($sourceDir);

foreach ($entries as $item) {
    if ($item === '.' || $item === '..') {
        continue;
    }

    $sourcePath = rtrim($sourceDir, '/') . '/' . $item;
    
    // Calculate relative path to preserve structure
    $relativePath = str_replace(rtrim($sourceDir, '/'), '', $sourcePath);
    $destPath     = rtrim($destDir, '/') . '/' . ltrim($relativePath, '/');

    if (rename($sourcePath, $destPath)) {
        // Success
    } else {
        // Log error or throw exception based on project needs
    }
}

Trade-offs and Pitfalls

Performance is a consideration when moving thousands of files. A simple loop in PHP is generally sufficient for typical application data, but if you are dealing with terabytes of assets, consider using command-line tools like rsync or mv executed via exec() or shell_exec() to leverage native OS-level efficiency and better error handling capabilities provided by the shell.

Another critical pitfall is race conditions. If a process is reading from the source directory while you are moving files, you might encounter errors if a file is locked or being modified. Always ensure the application locks the directory or that the migration happens during a low-traffic window.

Finally, verify that the destination path does not already contain a file with the same name as one being moved. The rename() function will fail if the target exists, returning false. If overwriting is acceptable, you must explicitly handle that logic; otherwise, rename the conflicting file first or skip the move.

Our network