如何将一个(或几个)文件从父文件夹复制到所有子文件夹中



我正试图找到一种简单的PHP方法,将一个文件(或两个文件(,比如Image.jpg复制到所有的子文件夹,而不管名称如何。似乎搞不清楚,会不会是之类的东西

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

这行得通吗?

我在搜索结果中没有看到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 );
}
}
}
}

相关内容

最新更新