以下是一个简单的php类,可以实现文件或者文件夹操作(复制,粘贴,剪贴,重命名,打开,编辑,保存,压缩,解压):
class FileManager {
private $baseDir;
public function __construct($baseDir) {
$this->baseDir = rtrim($baseDir, '/');
}
public function copy($from, $to) {
if (is_file($this->baseDir . '/' . $from)) {
copy($this->baseDir . '/' . $from, $this->baseDir . '/' . $to);
} else {
mkdir($this->baseDir . '/' . $to);
$files = scandir($this->baseDir . '/' . $from);
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
$this->copy($from . '/' . $file, $to . '/' . $file);
}
}
}
}
public function move($from, $to) {
if (is_file($this->baseDir . '/' . $from)) {
rename($this->baseDir . '/' . $from, $this->baseDir . '/' . $to);
} else {
mkdir($this->baseDir . '/' . $to);
$files = scandir($this->baseDir . '/' . $from);
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
$this->move($from . '/' . $file, $to . '/' . $file);
}
}
rmdir($this->baseDir . '/' . $from);
}
}
public function rename($oldName, $newName) {
rename($this->baseDir . '/' . $oldName, $this->baseDir . '/' . $newName);
}
public function open($filename) {
return file_get_contents($this->baseDir . '/' . $filename);
}
public function save($filename, $content) {
file_put_contents($this->baseDir . '/' . $filename, $content);
}
public function compress($path, $zipname) {
$zip = new ZipArchive;
if ($zip->open($this->baseDir . '/' . $zipname, ZipArchive::CREATE) === TRUE) {
if (is_file($this->baseDir . '/' . $path)) {
$zip->addFile($this->baseDir . '/' . $path, basename($path));
} else {
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($this->baseDir . '/' . $path), RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $file) {
if (!$file->isDir()) {
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($this->baseDir . '/'));
$zip->addFile($filePath, $relativePath);
}
}
}
$zip->close();
return true;
} else {
return false;
}
}
public function extract($zipname, $path = '') {
$zip = new ZipArchive;
if ($zip->open($this->baseDir . '/' . $zipname) === TRUE) {
$zip->extractTo($this->baseDir . '/' . $path);
$zip->close();
return true;
} else {
return false;
}
}
}
使用实例
$fm = new FileManager('/path/to/directory');
$fm->copy('filename.txt', 'newfile.txt'); // 复制文件
$fm->copy('dir1', 'dir2'); // 复制文件夹
$fm->move('oldfile.txt', 'newfile.txt'); // 剪切文件
$fm->move('olddir', 'newdir'); // 剪切文件夹
$fm->rename('oldfile.txt', 'newfile.txt'); // 重命名文件
$content = $fm->open('filename.txt'); // 打开文件
$fm->save('filename.txt', 'new content'); // 保存文件
$fm->compress('dir1', 'archive.zip'); // 压缩文件或文件夹
$fm->extract('archive.zip', 'extracted'); // 解压文件