我想使用PHP脚本将所有文件从一个文件夹复制到另一个文件夹。如果我有一个文件demo/index.php
,那么我想将index.php
复制到test/index.php
答案 0 :(得分:1)
您可以使用此功能递归复制文件和文件夹:
function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755))
{
$result=false;
if (is_file($source)) {
if ($dest[strlen($dest)-1]=='/') {
if (!file_exists($dest)) {
cmfcDirectory::makeAll($dest,$options['folderPermission'],true);
}
$__dest=$dest."/".basename($source);
} else {
$__dest=$dest;
}
$result=copy($source, $__dest);
@chmod($__dest,$options['filePermission']);
} elseif(is_dir($source)) {
if ($dest[strlen($dest)-1]=='/') {
if ($source[strlen($source)-1]=='/') {
//Copy only contents
} else {
//Change parent itself and its contents
$dest=$dest.basename($source);
if(!file_exists($dest)) mkdir($dest);
@chmod($dest,$options['filePermission']);
}
} else {
if ($source[strlen($source)-1]=='/') {
//Copy parent directory with new name and all its content
if(!file_exists($dest)) mkdir($dest,$options['folderPermission']);
@chmod($dest,$options['filePermission']);
} else {
//Copy parent directory with new name and all its content
if(!file_exists($dest)) mkdir($dest,$options['folderPermission']);
@chmod($dest,$options['filePermission']);
}
}
$dirHandle=opendir($source);
while($file=readdir($dirHandle))
{
if($file!="." && $file!="..")
{
if(!is_dir($source."/".$file)) {
$__dest=$dest."/".$file;
} else {
$__dest=$dest."/".$file;
}
//echo "$source/$file ||| $__dest<br />";
$result=smartCopy($source."/".$file, $__dest, $options);
}
}
closedir($dirHandle);
} else {
$result=false;
}
return $result;
}
然后以这种方式执行文件:
smartCopy('demo/index.php', 'test/index.php');
或文件夹:
smartCopy('demo/', 'test/');
答案 1 :(得分:0)
使用scandir()扫描目录中的所有文件,然后使用copy()
将文件复制到新目录中以下是复制所有文件的代码,试试这个......
<?php
$dir = 'img';
$files = scandir($dir);
///path to new directory..
$new_dir = 'img2';
foreach($files as $file)
{
if(!empty($file) && $file != '.' && $file != '..')
{
$source = $dir.'/'.$file;
$destination = $new_dir.'/'.$file;
if(copy($source, $destination))
{
echo "Copied $file...\n";
}
}
}
?>