Copy The Entire Contents Of A Directory To Another Directory in PHP


What is PHP ?

PHP, which stands for Hypertext Preprocessor, is a widely used server-side scripting language primarily designed for web development. It provides developers with a powerful and flexible platform for creating dynamic web pages and applications. PHP can be embedded within HTML code, allowing for seamless integration of server-side functionality with client-side elements. Its syntax is similar to C and Perl, making it relatively easy to learn and use for programmers familiar with those languages. PHP enables the execution of server-side scripts on a web server, generating dynamic content that can be delivered to the user's browser. It supports a wide range of databases, making it suitable for developing database-driven websites. Additionally, PHP offers a vast ecosystem of open-source libraries and frameworks, facilitating rapid development and enhancing code reusability. With its robust community support and extensive documentation, PHP continues to be a popular choice for web developers worldwide.

Copy The Entire Contents Of A Directory To Another Directory in PHP

Here we copy the entire contents of a directory to another directory by using the scandir() and by using RecursiveIteratorIterator class.

Method 1

Using scandir()

Then scandir() takes many parameters and returns the list of filenames in the directory if no error occurred.

Syntax

array scandir(string $directory, int $sorting_order = 
SCANDIR_SORT_ASCENDING, resource|null $context = null)
  • $directory (string): The path to the directory you want to scan.

  • $sorting_order (int, optional): Specifies the sorting order of the results. It can take one of the following values:

  • SCANDIR_SORT_ASCENDING (default): Sorts the results in ascending order.

  • SCANDIR_SORT_DESCENDING: Sorts the results in descending order.

  • SCANDIR_SORT_NONE: Does not perform any sorting.

  • $context (resource|null, optional): Specifies a context resource created with stream_context_create(). It is used to modify the behavior of the scandir() function. If not provided, null is used.

  • Return Value: The scandir() function returns an array of filenames and directories in the specified directory. It includes both regular files and directories. The resulting array includes the special entries . and .. representing the current directory and parent directory, respectively.

Example

Here is the example of how you can copy entire contents of a directory to another directory in PHP using the scandir().

<?php
function copyDirectory($source, $destination) {
   if (!is_dir($destination)) {
      mkdir($destination, 0755, true);
   }
   $files = scandir($source);
   foreach ($files as $file) {
      if ($file !== '.' && $file !== '..') {
         $sourceFile = $source . '/' . $file;
         $destinationFile = $destination . '/' . $file;
         if (is_dir($sourceFile)) {
            copyDirectory($sourceFile, $destinationFile);
         } else {
            copy($sourceFile, $destinationFile);
         }
      }
   }
}
$sourceDirectory = '/source/directory';
$destinationDirectory = '/destination/directory';
copyDirectory($sourceDirectory, $destinationDirectory);
?>

Output

There will be no output if the process is successful.

Explanation Of Code

The code defines a function named copyDirectory that is responsible for recursively copying the contents of a source directory to a destination directory. The function first checks if the destination directory doesn't exist and creates it using mkdir() if necessary. Then, it retrieves the list of files and directories in the source directory using scandir(). It iterates through each item, excluding the . and .. entries, and constructs the source and destination file paths. If the item is a directory, the function calls itself recursively with the new paths. If it is a file, it uses the copy() function to copy the file from the source to the destination. This process continues until all the contents of the source directory are copied to the destination directory, including subdirectories and their respective files. Finally, the function is called with the source and destination directories provided as arguments to perform the copy operation.

Method 2

Using RecursiveIteratorIterator class along with the RecursiveDirectoryIterator

Here we will use two classes in order to complete the task.

Syntax

bool mkdir(string $pathname, int $mode = 0777, bool $recursive = 
false, resource|null $context = null)
  • $pathname (string): The path of the directory to be created.

  • $mode (int, optional): The permissions to be set for the newly created directory. It is specified as an octal value.

  • $recursive (bool, optional): If set to true, it enables recursive creation of parent directories.

  • $context (resource|null, optional): Specifies a context resource created with stream_context_create().

  • Return Value: The mkdir() function returns true on success and false on failure.

Example

Here is an example of using the above method.

function copyDirectory($source, $destination) {
   if (!is_dir($destination)) {
      mkdir($destination, 0755, true);
   }
   $iterator = new RecursiveIteratorIterator(
      new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
      RecursiveIteratorIterator::SELF_FIRST
   );
   foreach ($iterator as $item) {
      if ($item->isDir()) {
         $dir = $destination . '/' . $iterator->getSubPathName();
         if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
         }
      } else {
         $file = $destination . '/' . $iterator->getSubPathName();
         copy($item, $file);
      }
   }
}
$sourceDirectory = '/source/directory';
$destinationDirectory = '/destination/directory';
copyDirectory($sourceDirectory, $destinationDirectory);

Output

There will be no output if the process is successful.

Explanation Of Code:

The code defines a function named copyDirectory that is responsible for recursively copying the contents of a source directory to a destination directory. The function first checks if the destination directory doesn't exist and creates it using mkdir() if necessary. Then, it retrieves the list of files and directories in the source directory using scandir(). It iterates through each item, excluding the . and .. entries, and constructs the source and destination file paths. If the item is a directory, the function calls itself recursively with the new paths. If it is a file, it uses the copy() function to copy the file from the source to the destination. This process continues until all the contents of the source directory are copied to the destination directory, including subdirectories and their respective files. Finally, the function is called with the source and destination directories provided as arguments to perform the copy operation.

Method 2

Using RecursiveIteratorIterator class along with the RecursiveDirectoryIterator

Here we will use two classes in order to complete the task.

Syntax

bool mkdir(string $pathname, int $mode = 0777, bool $recursive = 
false, resource|null $context = null)
  • $pathname (string): The path of the directory to be created.

  • $mode (int, optional): The permissions to be set for the newly created directory. It is specified as an octal value.

  • $recursive (bool, optional): If set to true, it enables recursive creation of parent directories.

  • $context (resource|null, optional): Specifies a context resource created with stream_context_create().

  • Return Value: The mkdir() function returns true on success and false on failure.

Example

Here is an example of using the above method.

function copyDirectory($source, $destination) {
   if (!is_dir($destination)) {
      mkdir($destination, 0755, true);
   }
   $iterator = new RecursiveIteratorIterator(
      new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
      RecursiveIteratorIterator::SELF_FIRST
   );
   foreach ($iterator as $item) {
      if ($item->isDir()) {
         $dir = $destination . '/' . $iterator->getSubPathName();
         if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
         }
      } else {
         $file = $destination . '/' . $iterator->getSubPathName();
         copy($item, $file);
      }
   }
}
$sourceDirectory = '/source/directory';
$destinationDirectory = '/destination/directory';
copyDirectory($sourceDirectory, $destinationDirectory);

Explanation of Code

In this approach, the RecursiveDirectoryIterator is used to iterate through the directory structure, including all subdirectories and files. The RecursiveIteratorIterator helps in traversing the iterator recursively. It skips the . and .. entries using the SKIP_DOTS flag. Inside the loop, it checks if the current item is a directory. If so, it creates the corresponding directory in the destination path using mkdir() if it doesn't already exist. If the item is a file, it constructs the destination file path and uses copy() to copy the file. This method eliminates the need for a separate recursive function and simplifies the code by leveraging the power of the built-in PHP iterator classes.

Conclusion

In conclusion, both methods can achieve the desired result, but the second method using iterators offers a more elegant and efficient solution, particularly for scenarios involving large directory structures. However, the choice between the two methods ultimately depends on the specific requirements and preferences of the developer.

Updated on: 28-Jul-2023

849 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements