我找到了Rich Rodecker的这段代码(http://www.visible-form.com/blog/copy-directory-in-php/)。它工作得很好,除了如果文件夹中有文件,它将它们转换成文件夹。
下面是上面链接的PHP代码片段。
function copyr($source, $dest){
// Simple copy for a file
if (is_file($source)) {
$c = copy($source, $dest);
chmod($dest, 0777);
return $c;
}
// Make destination directory
if (!is_dir($dest)) {
$oldumask = umask(0);
mkdir($dest, 0777);
umask($oldumask);
}
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == "." || $entry == "..") {
continue;
}
// Deep copy directories
if ($dest !== "$source/$entry") {
copyr("$source/$entry", "$dest/$entry");
}
}
// Clean up
$dir->close();
return true;
}
copyr("copy","copy2");
例如
是当前网站的结构- Root
- - index.php (Code here that runs copy function)
- - copy (DIR)
- - - index.html (Dummy content in file)
当我运行index.php时,它创建了这个:
- Root
- - index.php (Code here that runs copy function)
- - copy (DIR)
- - - index.html (HTML)
- - copy2 (DIR)
- - - index.html (DIR)
- - - - EMPTY
谁能看出问题是什么并提供解决方案?我希望能够指定一个目录,并让它备份整个目录,包括子文件夹和文件。
From PHP manual:
注意is_file()返回false如果父目录没有+x套给你;这是有道理的,但其他函数,如readdir()似乎没有这个限制。最终的结果是你可以循环遍历目录中的文件,但is_file()总是会失败。
检查源目录的权限