Php класс для автоматического создания всех нужных директорий из переданного пути.
Класс для создания директории
10.11.2015
Скрипт устарел! Нужно использовать mkdir, передав третьим параметром TRUE (разрешение рекурсивного создания директорий)
mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = FALSE [, resource $context ]]] ) : bool
Также есть проблема с makeSafe (проверки пути на безопасность), по умолчанию отрезаются все ., даже в имени домена.
dir.php (Download)
<?
class soDir
{
protected $_sPath = '';
function __construct($sPath)
{
$this->_sPath = $this->_makeSafe($sPath);
}
protected function _makeSafe($sPath)
{
return $sPath;
/* $ds = ( DS == '\\' ) ? '\\'.DS : DS;
$regex = array('#[^A-Za-z0-9:\.\_\-'.$ds.' ]#'); // Oddler. Добавил ".". Т.к. часто бывают папки с названием домена. Но не уверен, что это секюрно
return preg_replace($regex, '', $sPath);*/
}
public function setPath($sPath)
{
$this->_sPath = $this->_makeSafe($sPath);
}
public function getPath()
{
return $this->_sPath;
}
public function exists($sPath='')
{
$sPath = $sPath?$sPath:$this->_sPath;
return file_exists($sPath);
}
public function writable($sPath)
{
$sPath = $sPath?$sPath:$this->_sPath;
return is_writable($sPath);
}
/*
Create a folder -- and all necessary parent folders
*/
public function create($path = '', $mode = 0755)
{
$path = $path?$path:$this->_sPath;
// echo '$path' . $path.'<br />';
//$path = c_Path::clean($path);
$nested = 0;
// Check if parent dir exists
$parent = dirname($path);
if (!$this->exists($parent))
{
$nested++;
if (($nested > 20) || ($parent == $path) )
{
die('Infinite loop detected');
$nested--;
return false;
}
// Create the parent directory
if ($this->create($parent, $mode) !== true)
{
// JFolder::create throws an error
$nested--;
return false;
}
// OK, parent directory has been created
$nested--;
}
// Check if dir already exists
if ($this->exists($path))
{
return true;
}
// First set umask
$origmask = @ umask(0);
// Create the path
if (!$ret = @mkdir($path, $mode))
{
@ umask($origmask);
die('Could not create directory! Path: ' . $path);
return false;
}
// Reset umask
@ umask($origmask);
return true;
}
public static function makeDir($sPath)
{
// echo $sPath.'<br />';
$oDir = new soDir($sPath);
if(!$oDir->exists())
{
$oDir->create();
}
return $oDir;
}
}
?>