Recursive Copy of Directory

前端 未结 14 967
花落未央
花落未央 2020-12-08 15:14

On my old VPS I was using the following code to copy the files and directories within a directory to a new directory that was created after the user submitted their form.

14条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 15:34

    The Symfony's FileSystem Component offers a good error handling as well as recursive remove and other useful stuffs. Using @OzzyCzech's great answer, we can do a robust recursive copy this way:

    use Symfony\Component\Filesystem\Filesystem;
    
    // ...
    
    $fileSystem = new FileSystem();
    
    if (file_exists($target))
    {
        $this->fileSystem->remove($target);
    }
    
    $this->fileSystem->mkdir($target);
    
    $directoryIterator = new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS);
    $iterator = new \RecursiveIteratorIterator($directoryIterator, \RecursiveIteratorIterator::SELF_FIRST);
    foreach ($iterator as $item)
    {
        if ($item->isDir())
        {
            $fileSystem->mkdir($target . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
        }
        else
        {
            $fileSystem->copy($item, $target . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
        }
    }
    

    Note: you can use this component as well as all other Symfony2 components standalone.

提交回复
热议问题