簡體   English   中英

如何將 1 個(或幾個)文件從父文件夾復制到所有子文件夾

[英]How to copy 1 (or a couple) files from parent folder into all subfolder

我試圖找出一個簡單的 PHP 方法來復制一個文件(或幾個),例如 Image.jpg 到所有子文件夾,盡管名稱。 似乎無法弄清楚,會不會是這樣的

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

copy($file, $subdirs);

?>

這行得通嗎?

我在搜索結果中沒有看到 PHP 版本,所以這就是我問的原因

要使用DirectoryIterator class 你可以這樣做。

# 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 );
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM