php - 如何将 1 个(或几个)文件从父文件夹复制到所有子文件夹
问题描述
我试图找出一种简单的 PHP 方法来复制 1 个文件(或几个),例如 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 );
}
}
}
}
推荐阅读
- python - 接收 pd.read_csv 的 TypeError -> 由不同的名称解决?
- android - Kotlin URL().readText() 使应用程序崩溃
- javascript - 通过循环使用逻辑
- wordpress - woocommerce 免费送货不适用于最低订单
- python - Python - 读取和打印大 .txt 文件的前 n 行
- sql - 升序求和 sql Oracle
- c# - 有没有办法将一个游戏对象从一个场景复制到另一个场景?
- arrays - Ruby .store 函数将哈希值从数组更改为单个值
- list - 哈斯克尔。按元组列表中的第二个元素排序
- python - 如何将 Numpy 百分位数与 Pandas 数据一起使用