Copy all contents of one directory to another directory in PHP

WBOY
Release: 2023-08-29 14:42:01
forward
2031 people have browsed it

Copy all contents of one directory to another directory in PHP

What is PHP?

PHP stands for Hypertext Preprocessor and is a widely used server-side scripting language primarily used for web development. It provides developers with a powerful and flexible platform to create dynamic web pages and applications. PHP can be embedded in 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 these languages. PHP allows server-side scripts to be executed on a web server, generating dynamic content that can be delivered to the user's browser. It supports a variety of databases and is suitable for developing database-driven websites. Additionally, PHP offers a vast ecosystem of open source libraries and frameworks that facilitate rapid development and enhance code reusability. With its strong community support and extensive documentation, PHP remains a popular choice among web developers worldwide.

PHP Copy the entire contents of one directory to another directory

Here, we use scandir() and the RecursiveIteratorIterator class to copy the entire contents of one directory to another directory.

method 1

Use scandir()

Then scandir() accepts a number of arguments and, if no errors occur, returns a list of file names in the directory.

grammar

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

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

  • SCANDIR_SORT_ASCENDING (default): Sort results in ascending order.

  • SCANDIR_SORT_DESCENDING: Sort results in descending order.

  • SCANDIR_SORT_NONE: No sorting is performed.

  • $context (resource|null, optional): Specifies the context resource created using 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 file names and directories in the specified directory. It includes regular files and directories. The resulting array contains special entries. and .. represent the current directory and parent directory respectively.

Example

Here is an example of how to use scandir() to copy the entire contents of one directory to another directory in PHP.

<?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);
?>
Copy after login

Output

There will be no output if the process is successful.
Copy after login
Copy after login

Code description

This code defines a function named copyDirectory, which is responsible for recursively copying the contents of the source directory to the target directory. The function first checks if the target directory does not exist and creates it using mkdir() if necessary. It then uses scandir() to retrieve a list of files and directories in the source directory. It iterates through each item, excluding . and .. entries, and constructs the source and destination file paths. If the item is a directory, the function calls itself recursively with the new path. If it is a file, use the copy() function to copy the file from the source to the destination. This process continues until all contents of the source directory have been copied to the target 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 the RecursiveIteratorIterator class with RecursiveDirectoryIterator

Here we will use two classes to complete the task.

grammar

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

  • $mode (int, optional): Permissions to set for newly created directories. It is specified as an octal value.

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

  • $context (resource|null, optional): Specifies the context resource created using stream_context_create().

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

Example

Here is an example 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);
Copy after login
Copy after login

Output

There will be no output if the process is successful.
Copy after login
Copy after login

Code description:

This code defines a function named copyDirectory, which is responsible for recursively copying the contents of the source directory to the target directory. The function first checks if the target directory does not exist and creates it using mkdir() if necessary. It then uses scandir() to retrieve a list of files and directories in the source directory. It iterates through each item, excluding . and .. entries, and constructs the source and destination file paths. If the item is a directory, the function calls itself recursively with the new path. If it is a file, use the copy() function to copy the file from the source to the destination. This process continues until all contents of the source directory have been copied to the target 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.

方法2

将 RecursiveIteratorIterator 类与 RecursiveDirectoryIterator 一起使用

这里我们将使用两个类来完成任务。

语法

bool mkdir(string $pathname, int $mode = 0777, bool $recursive = 
false, resource|null $context = null)
Copy after login
Copy after login
  • $pathname(字符串):要创建的目录的路径。

  • $mode(int,可选):为新创建的目录设置的权限。它被指定为八进制值。

  • $recursive(布尔型,可选):如果设置为 true,则启用父目录的递归创建。

  • $context(resource|null,可选):指定使用stream_context_create()创建的上下文资源。

  • 返回值:mkdir() 函数在成功时返回 true,在失败时返回 false。

示例

这里是使用上述方法的一个例子。

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);
Copy after login
Copy after login

代码说明

在此方法中,RecursiveDirectoryIterator 用于迭代目录结构,包括所有子目录和文件。 RecursiveIteratorIterator 有助于递归地遍历迭代器。它会跳过 .和 .. 使用 SKIP_DOTS 标志的条目。在循环内,它检查当前项是否是目录。如果是这样,它会使用 mkdir() 在目标路径中创建相应的目录(如果该目录尚不存在)。如果该项目是文件,它将构造目标文件路径并使用 copy() 复制文件。此方法消除了对单独递归函数的需要,并通过利用内置 PHP 迭代器类的功能简化了代码。

结论

综上所述,两种方法都可以达到预期的结果,但第二种使用迭代器的方法提供了更优雅、更高效的解决方案,特别是对于涉及大型目录结构的场景。不过,这两种方法的选择最终取决于开发者的具体要求和偏好。

The above is the detailed content of Copy all contents of one directory to another directory in PHP. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!