首页 > 解决方案 > 如何将 1 个(或几个)文件从父文件夹复制到所有子文件夹

问题描述

我试图找出一种简单的 PHP 方法来复制 1 个文件(或几个),例如 Image.jpg 到所有子文件夹,尽管名称。似乎无法弄清楚,会不会是这样的

<?php
$file = 'image.jpg';
$subdirs = '/*'; // I Actually need to go 2 subdirectories below

copy($file, $subdirs);

?>

这行得通吗?

我在搜索结果中没有看到 PHP 版本,所以这就是我问的原因

标签: php

解决方案


要使用这个DirectoryIterator类,你可以做这样的事情。

# permit auto-delete of any copied files, set false to disable.
$debug=true;

$depth=1;// limit recursion depth to this...

/*
    The target directory "textfiles" has 3 subfolders.
    Each subfolder initially had a single file - file.txt
    
    The files to copy are html files in a nearby directory
*/
$dir=sprintf('%s/textfiles/',__DIR__ );

$files=array(
    sprintf('%s/temp/page1.html', __DIR__ ),
    sprintf('%s/temp/page2.html', __DIR__ ),
);

/* utility to determine if the given dir is a dot/dbl dot */
function isDot( $dir=true ){
    return basename( $dir )=='.' or basename( $dir )=='..';
}


/*
    Iterate through the child folders and copy ALL files from given $files
    array into each subfolder. If the file already exists do nothing.
*/
$dirItr=new RecursiveDirectoryIterator( $dir, RecursiveDirectoryIterator::KEY_AS_PATHNAME );
$recItr=new RecursiveIteratorIterator( $dirItr, RecursiveIteratorIterator::CHILD_FIRST );
$recItr->setMaxDepth( $depth );
    
foreach( $recItr as $obj => $info ) {

    if( $info->isDir() && !isDot( $info->getPathname() ) ){
        
        $path=realpath( $info->getPathname() );
        
        #copy each file
        foreach( $files as $file ){
            
            # determine what the full filepath would be - test if it already exists
            $target=sprintf('%s%s%s', $path, DIRECTORY_SEPARATOR, basename( $file ));
            
            if( !file_exists( $target ) ){
                $status=copy( $file, $target );
                printf('<div>"%s" copied to "%s" - %s</div>',basename( $file ), $path, $status ? 'OK' : 'Failed' );
            }else{
                printf('<div>The file "%s" already exists in the folder "%s"</div>',basename( $file ),$path);
                
                # to test functionality, once file is copied 1st time it will be deleted 2nd time if debug is true
                if( $debug ) @unlink( $target );
            }
        }
    }
}

推荐阅读