In PHP, the mkdir function creates a directory. It cannot create a directory recursively. We need to traverse the directory and then call mkdir. Let’s take a look at the operation method.
Example
The code is as follows |
Copy code |
代码如下 |
复制代码 |
/**
* Makes directory and returns BOOL(TRUE) if exists OR made.
*
* @param $path Path name
* @return bool
*/
function rmkdir($path, $mode = 0755) {
$path = rtrim(preg_replace(array("/\/", "//{2,}/"), "/", $path), "/");
$e = explode("/", ltrim($path, "/"));
if(substr($path, 0, 1) == "/") {
$e[0] = "/".$e[0];
}
$c = count($e);
$cp = $e[0];
for($i = 1; $i < $c; $i++) {
if(!is_dir($cp) && !@mkdir($cp, $mode)) {
return false;
}
$cp .= "/".$e[$i];
}
return @mkdir($path, $mode);
}
?>
|
/**
* Makes directory and returns BOOL(TRUE) if exists OR made.
*
* @param $path Path name
* @return bool
*/
function rmkdir($path, $mode = 0755) {
$path = rtrim(preg_replace(array("/\/", "//{2,}/"), "/", $path), "/");
$e = explode("/", ltrim($path, "/"));
If(substr($path, 0, 1) == "/") {
$e[0] = "/".$e[0];
}
$c = count($e);
$cp = $e[0];
for($i = 1; $i < $c; $i++) {
If(!is_dir($cp) && !@mkdir($cp, $mode)) {
return false;
}
$cp .= "/".$e[$i];
}
Return @mkdir($path, $mode);
}
?>
|
Example 2
Somehow the recursive version of mkdir didn't work for me on Mac and the workaraounds listed
代码如下 |
复制代码 |
function mkdir_r($dirName, $rights=0777){
$dirs = explode('/', $dirName);
$dir='';
foreach ($dirs as $part) {
$dir.=$part.'/';
if (!is_dir($dir) && strlen($dir)>0)
mkdir($dir, $rights);
}
}
?>
Tested and works ;)
|
below alsow didn't work for me, so heres my solution:
The code is as follows |
Copy code |
function mkdir_r($dirName, $rights=0777){
$dirs = explode('/', $dirName);
$dir='';
foreach ($dirs as $part) {
$dir.=$part.'/';
If (!is_dir($dir) && strlen($dir)>0)
mkdir($dir, $rights);
}
}
?>
Tested and works ;)
|
例3
代码如下
代码如下 |
复制代码 |
function mkdirs($dir)
{
if(!is_dir($dir))
{
if(!mkdirs(dirname($dir))){
return false;
}
if(!mkdir($dir,0777)){
return false;
}
}
return true;
}
function rmdirs($dir)
{
$d = dir($dir);
while (false !== ($child = $d->read())){
if($child != '.' && $child != '..'){
if(is_dir($dir.'/'.$child))
rmdirs($dir.'/'.$child);
else unlink($dir.'/'.$child);
}
}
$d->close();
rmdir($dir);
}
|
|
复制代码
|
function mkdirs($dir) |
{
if(!is_dir($dir))
{
if(!mkdirs(dirname($dir))){
return false;
}
if(!mkdir($dir,0777)){
return false;
}
}
}
function rmdirs($dir)
{
$d = dir($dir);
while (false !== ($child = $d->read())){
if($child != '.' && $child != '..'){
if(is_dir($dir.'/'.$child))
rmdirs($dir.'/'.$child);
else unlink($dir.'/'.$child);
}
}
$d->close();
rmdir($dir);
}
三个创建目录的函数都有自己的优点,这里我也没有一个个测试了,只使用了第二个感觉非常的不错。
http://www.bkjia.com/PHPjc/633126.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/633126.htmlTechArticle在php中mkdir函数是创建目录它自身是不可以递归创建目录了,我们需要遍历进行目录然后调用mkdir即可,下面来看一下操作方法。 例 代码如...