2015-06-18 27 views
1

如何使用PHP的mkdir函數遞歸跳過現有的目錄,並建立從string $pathname如何遞歸使用PHP mkdir函數跳過現有目錄並創建新目錄?

// works fine if directories don't exist 
mkdir($root_dir . '/demo/test/one', 0775, true); 

// It will throw error - Message: mkdir(): File exists 
mkdir($root_dir . '/demo/test/two', 0775, true); 

如何解決新的?

+4

怎麼樣'!is_dir'? http://php.net/manual/en/function.is-dir.php – chris85

+0

在這個例子中,我試圖創建兩個不同的目錄 - 一個和兩個演示/測試。因此,is_dir將返回FALSE,但mkdir將失敗,因爲demo/test已經存在。 –

+0

你不能。如果該目錄存在,它將返回false,因此在嘗試創建目錄之前,您必須測試該目錄是否存在。 –

回答

0

您的代碼應工作,因爲它是,在問題發生時,/如果你運行它第二次按@ chris85的建議,你可以檢查他們事先存在。

<?php 
// given 
$root_dir = __DIR__; 

// and you want to have these 
$dirs = [ 
    $root_dir . '/demo/test/one', 
    $root_dir . '/demo/test/tow', 
    $root_dir . '/demo/test/three', 
    $root_dir . '/demo/test/four', 
    $root_dir . '/demo/test/and/so/on', 
]; 

// just check if they're not exists and then create them 
foreach ($dirs as $dir) { 
    if (!is_dir($dir)) { 
     mkdir($dir, 0775, true); 
    } 
} 
0

檢查與is_dir如果該目錄已經存在:

if(!is_dir($pathname)) { 
    mkdir($pathname, 0775, true); 
}