复制移动整个文件夹php代码三种写法:
一、使用递归的方式复制和移动文件夹
1、复制文件夹
function copyall($filesrc, $newpath) {
$dir = opendir($filesrc);
@mkdir($newpath);
while (($file = readdir($dir)) !== false) {
if ($file !== '.' && $file !== '..') {
if (is_dir($filesrc . '/' . $file)) {
copyall($filesrc . '/' . $file, $newpath . '/' . $file);
} else {
copy($filesrc . '/' . $file, $newpath . '/' . $file);
}
}
}
closedir($dir);
}2、移动文件夹
function moveall($filesrc, $newpath) {
$dir = opendir($filesrc);
@mkdir($newpath);
while (($file = readdir($dir)) !== false) {
if ($file !== '.' && $file !== '..') {
if (is_dir($filesrc . '/' . $file)) {
moveall($filesrc . '/' . $file, $newpath . '/' . $file);
} else {
rename($filesrc . '/' . $file, $newpath . '/' . $file);
}
}
}
closedir($dir);
}二、使用迭代的方式复制和移动文件夹
1、复制文件夹
function copyall($filesrc, $newpath) {
$dirStack = array($filesrc);
$newpathStack = array($newpath);
while (!empty($dirStack)) {
$currentSrc = array_pop($dirStack);
$currentDst = array_pop($newpathStack);
@mkdir($currentDst);
$dir = opendir($currentSrc);
while (($file = readdir($dir)) !== false) {
if ($file !== '.' && $file !== '..') {
if (is_dir($currentSrc . '/' . $file)) {
array_push($dirStack, $currentSrc . '/' . $file);
array_push($newpathStack, $currentDst . '/' . $file);
} else {
copy($currentSrc . '/' . $file, $currentDst . '/' . $file);
}
}
}
closedir($dir);
}
}2、移动文件夹
function moveall($filesrc, $newpath) {
$dirStack = array($filesrc);
$newpathStack = array($newpath);
while (!empty($dirStack)) {
$currentSrc = array_pop($dirStack);
$currentDst = array_pop($newpathStack);
@mkdir($currentDst);
$dir = opendir($currentSrc);
while (($file = readdir($dir)) !== false) {
if ($file !== '.' && $file !== '..') {
if (is_dir($currentSrc . '/' . $file)) {
array_push($dirStack, $currentSrc . '/' . $file);
array_push($newpathStack, $currentDst . '/' . $file);
} else {
rename($currentSrc . '/' . $file, $currentDst . '/' . $file);
}
}
}
closedir($dir);
}
}三、使用 PHP 的函数库(FilesystemIterator 和 RecursiveDirectoryIterator)复制和移动文件夹
1、复制文件夹
function copyall($filesrc, $newpath) {
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($filesrc, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $file) {
$target = $newpath . '/' . $iterator->getSubPathName();
if ($file->isDir()) {
mkdir($target);
} else {
copy($file, $target);
}
}
}2、移动文件夹
function copyall($filesrc, $newpath) {
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($filesrc, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $file) {
$target = $newpath . '/' . $iterator->getSubPathName();
if ($file->isDir()) {
mkdir($target);
} else {
rename($file, $target);
}
}
}如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛