I did this for practice. I really would appreciate some feedback. Thanks.
PHP Code:
<?php
// DirectoryCopier.php
/**
* DirectoryCopier
* Makes a copy of an existing directory and it's contents.
*
* @author jasondfr
* @param string $dir Existing Directory
* @param string $copyto Directory to copy to
*
* @notes Bad things happen when copying a direcotry into itself ->
* It would be nice to allow this. strpos() is used in the setCopyto method
* to check for this. However, I'm not sure this is the best way.
*
*/
class DirectoryCopier extends DirectoryIterator {
protected $_dir;
protected $_copyto = null;
protected $_result = false;
public function __construct($dir, $copyto = null) {
$this->_dir = realpath($dir);
if (!is_null($copyto)) {
$this->setCopyTo($copyto);
}
parent::__construct($this->_dir);
}
public function setCopyTo($copyto) {
$this->_copyto = (string) rtrim($copyto, '/');
if (strpos($this->_copyto, $this->_dir) !== false) {
throw new Exception('Cannot copy into new directory within
directory being copied'
);
}
if ( is_dir($this->_copyto) ) {
$this->_copyto = realpath($this->_copyto);
}
}
public function getCopyTo() {
return $this->_copyto;
}
public function copy() {
if (is_null($this->_copyto)) {
throw new Exception('You must specify a directory to copy to.'
);
}
if (!is_dir($this->_copyto)) {
if (!mkdir($this->_copyto)) {
throw new Exception('Cannot create directory to copy into.
Check permissions and syntax.'
);
}
}
foreach ( $this as $file ) {
if (!$file->isdot()) {
if ($file->isFile()) {
$this->_result = copy($file->getPathName(),
$this->_copyto . '/' . $file->getFilename()
);
if ($this->_result !==true) {
break;
}
} elseif ($file->isDir()) {
$dir = new DirectoryCopier($file->getPathName(),
$this->_copyto . '/' . $file);
$dir->copy();
} else {
continue;
}
}
}
return $this->_result;
}
}
Usage:
PHP Code:
<?php
require_once('DirectoryCopier.php');
$dir = '/home/user/dir';
$copyto = '/home/directory';
$dircopier = new DirectoryCopier($dir, $copyto);
try {
if ($dircopier->copy())
echo 'Successful';
else
echo 'Not Successful';
} catch (Exception $e) {
print_r($e);
}
exit;
Bookmarks